Java Data Types

Category: Java   Tags: Java, Java Basic, Java Data Types

Java is a strongly typed language, every variable has a type, every expression has a type, and every type is strictly defined. The Java compiler checks all expressions and parameters to make sure that the types are compatible. If there is any type mismatches, it will stop compiling the code and throws error.

Java Data Types

There are two data types in Java:

  • Primitive Data Types
  • Object or Reference Data Types

Primitive Data Types

Java defines eight primitive types of data: byte, short, int, long, char, float, double and boolean.

byte

  • Smallest integer type
  • A signed 8-bit type that has a range from –128 to 127
  • Useful when you are working with a stream of data from a network or file
  • Default value is 0
  • Example byte b = 90;

short

  • Signed 16-bit type
  • Range from –32,768 to 32,767
  • Default value is 0
  • Example short s = 1020;

int

  • A signed 32-bit type
  • Range from –2,147,483,648 to 2,147,483,647
  • Default value is 0
  • Example int i = 2000;

long

  • A signed 64-bit data type
  • Used when int type is not large enough to hold the expected value
  • It has a minimum value of -263 and a maximum value of 263-1
  • Example long l = 10000L;

char

  • It is a single 16-bit Unicode character
  • Used to store a single character
  • It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive)
  • Example char c = 'a';

float

  • It is a single-precision 32-bit IEEE 754 floating point
  • Use it if you need to save memory in large arrays of floating point numbers
  • This data type should never be used for precise values, such as currency
  • Example float f = 200.10f;

double

  • The double data type is a double-precision 64-bit IEEE 754 floating point
  • This data type should never be used for precise values, such as currency
  • Default value is 0.0d
  • Example double d = 20.50;

boolean

  • A boolean data type has ony two possible values: true or false
  • This data type represents one bit of information
  • Default value is false
  • Example boolean b = true;

Object or Reference Data Types

In Java an object or reference can be created using a predefined classes as below:

MyClass ref = new MyClass();

Here, ref is reference to our Java class MyClass.