Java – Data Types

Understanding what data types are accessible and how data is stored, retrieved, and manipulated in a programming language is one of the most crucial aspects of learning any programming language. The operating system allocates memory to a variable based on its data type and determines what can be placed in the reserved memory.

In Java, there are two sorts of data types, which are listed below:

  • Boolean, char, byte, short, int, long, float, and double are examples of primitive data types.
  • Strings, Interfaces, Classes, etc are examples of non-primitive data types.

Primitive Data Types

Java’s basic data types are detailed in the table below:

Data Types Default value Memory Size Description
boolean false 1 bit Stores true or false values.
char ‘\u0000’ 2 byte Stores a single character/letter or ASCII value.
byte 0 1 byte Stores integer values from -128 to 127.
short 0 2 byte Stores integer values from -32,768 to 32,767.
int 0 4 byte Stores integer values from -231 to 231-1.
long 0L 8 byte Stores integer values from -263 to 263-1.
float 0.0f 4 byte Stores floating values from 1.40239846 x 10-45 to 3.40282347 x 1038.
double 0.0d 8 byte Stores floating values from 4.9406564584124654 x 10-324 to 1.7976931348623157 x 10308.

 

In the example below, a Java application is used to build several primitive data types.

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

Click here to use the online java Complier.

 

Next: Java – Type Casting

Leave a Reply

Your email address will not be published. Required fields are marked *