Data Types in Java with Examples

In Java, data types specify the type of data that a variable can hold.

Here is an example that shows how data types are used in Java:

String stringValue = "Hello"
byte byteNumber = 100;
short shortNumber = 1344;
int intNumber = 1034345;
long longNumber = 1092929292;
float floatNumber = 10;
double doubleNumber = 20.34;
boolean boolValue = true;
char charValue = 'n';


In the above example, String, byte, short, int, long, float, double, boolean, char are data types.

There are two types of data types in Java:

  1. Primitive data types
  2. Non-primitive data types


Primitive Data Types

Primitive types are the most basic data types in Java. They are built-in and available in the Java language. There are eight primitive data types in Java:

Data TypeSizeDescription
byte
8 bit
Can store value from -128 to 127
short
16-bit
Can store value from -32,768 to 32,767
int
32-bit
Can store value from -2,147,483,648 to 2,147,483,647
long
64-bit
Can store from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float
32-bit single-precision
Store value from 3.402,823,5 E+38 to 1.4 E-45
double
64-bit double-precision
Can store value from 1.797,693,134,862,315,7 E+308 to 4.9 E-324
boolean
1-bit
Can store true or false
char
16-bit
Can store unicode character value from '\u0000' (or 0) to '\uffff'


Example:

public class PrimitiveDatatypesExample {

    public static void main(String[] args) {

        byte byteNumber = 100;
        short shortNumber = 1344;
        int intNumber = 1034345;
        long longNumber = 1092929292;
        float floatNumber = 10;
        double doubleNumber = 20.34;
        boolean boolValue = true;
        char charValue = 'a';

        System.out.println(byteNumber);
        System.out.println(shortNumber);
        System.out.println(intNumber);
        System.out.println(longNumber);
        System.out.println(floatNumber);
        System.out.println(doubleNumber);
        System.out.println(boolValue);
        System.out.println(charValue);
    }
}


The output of the above code is as follows:

100
1344
1034345
1092929292
10.0
20.34
true
a


Non-primitive Data Types

Non-primitive data types are also called reference types. A reference data type can be used to refer to String, Classes, and Arrays type. A reference type does not store values but store reference to that value in memory.

String text = new String();
Student student = new Student();
Dog dog = new Dog();
User user = new User();

The default value of a reference variable is null.


Java is Strongly Typed and Type-safe

Java is strongly typed language which means a variable declared with an integer data type cannot be assigned a floating point number (a number with a decimal point).

Java language is designed to be type-safe which means all the data types declared in the program are checked during compilation so as to ensure that the operations are performed on right kind of data.