Java Tutorial Java Advanced Java References

Java - Data Types



One of the most important parts of learning any programming language is to understand what are the available data types, and how data is stored, accessed and manipulated in that language. Based on the data type of a variable, the operating system allocates memory to the variable and decides what can be stored in the reserved memory.

There are two types of data types in Java which are categorized below:

  • Primitive Data Types: This includes boolean, char, byte, short, int, long, float and double.
  • Non-primitive Data Types: This includes String, Interfaces, Classes etc.

Primitive Data Types

The table below describes primitive data types of Java in detail:

Data TypesDefault valueMemory SizeDescription
booleanfalse1 bitStores true or false values.
char'\u0000'2 byteStores a single character/letter or ASCII value.
byte01 byteStores integer values from -128 to 127.
short02 byteStores integer values from -32,768 to 32,767.
int04 byteStores integer values from -231 to 231-1.
long0L8 byteStores integer values from -263 to 263-1.
float0.0f4 byteStores floating values from 1.40239846 x 10-45 to 3.40282347 x 1038.
double0.0d8 byteStores floating values from 4.9406564584124654 x 10-324 to 1.7976931348623157 x 10308.

The example below shows how to create different primitive data types in a Java program.

public class MyClass {
  public static void main(String[] args) {       
    boolean i = true;
    char j = 'A';
    byte k = 10;
    short l = 10;
    int m = 10;
    long n = 10L;
    float o = 10.5f;
    double p = 10.5d; 

    //printing data types
    System.out.println("i is a boolean. i = " + i); 
    System.out.println("j is a char. j = " + j); 
    System.out.println("k is a byte. k = " + k); 
    System.out.println("l is a short. l = " + l); 
    System.out.println("m is an int. m = " + m); 
    System.out.println("n is a long. n = " + n); 
    System.out.println("o is a float. o = " + o); 
    System.out.println("p is a double. p = " + p); 
  }
}

The output of the above code will be:

i is a boolean. i = true
j is a char. j = A
k is a byte. k = 10
l is a short. l = 10
m is an int. m = 10
n is a long. n = 10
o is a float. o = 10.5
p is a double. p = 10.5

5