Datatypes in Java with Examples

A data type is the type of value a variable can store. 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).

Example

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';

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 Type Size Description
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

package com.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);
    }
}
Output
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.

Example

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

Note: The default value of a reference variable is null.

Java is Type-safe

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.