Data Types in Java Explained

  • Post author:
  • Post category:Java / Java Basic
  • Post last modified:July 7, 2021
  • Reading time:2 mins read

In Java, data types refer to the type of data that can be stored in variables. Because Java is a tightly typed language, you must define the datatype of variables before using them, and you cant not assign incompatible datatypes because it will publish compiler error.

There are two types of data types in java.

  • Primitive data types
  • Referenced data types.

Primitive data types

The datatypes defined by the Java language are known as primitive data types.

Java has eight primitive data types.

Data TypeDefault ValueDefault sizeRange
booleanfalse1 bit true or false.
char‘\u0000’2 byte1 character
byte01 byte-128 and 127
short02 Byte-32,768 to 32767
int04 byte-2,147,483,648
to
2,147,483,647
long0L8 byte-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float0.0f4 byte6 to 7 decimal digits
double0.0d8 byte15 decimal digits

Let’s see some example about data types:

Adding two integers

package com.sync;

public class DataTypeDemo {

    public static void main(String[] args) {
        int a=100;
        int b=200;
        int c=a+b;
        System.out.println(c);
    }
}
// Output: 300

Assigning int to double(Widening)

In this case, we’ll convert int to double. Due to the fact that double requires more memory than int. This is called widening.

package com.sync;

public class DataTypeDemo {

    public static void main(String[] args) {
        int a=100;
        double b=a;
        System.out.println(a);
        System.out.println(b);
    }
}
Output: 100
        100.0

Assigning double to int(Narrowing or typecasting)

In this case, we’ll convert double to int. Due to the fact that double requires more memory than int. This is called the operation of Narrowing.

package com.sync;

public class DataTypeDemo {

    public static void main(String[] args) {
        double a=100.0;
        int b=(int) a;
        System.out.println(a);
        System.out.println(b);
    }
}
// Output: 100.0
           100

Assinging int to byte(Overflow condition)

When you convert an int to a byte and the value of the int exceeds the size of the byte, you get an overflow.

package com.sync;

public class DataTypeDemo {

    public static void main(String[] args) {
        int a=300;
        byte b=(byte) a;
        System.out.println(a);
        System.out.println(b);
    }
}
// Output: 300
           44

Reference data types

Reference data types are those data types which are provided as class by Java AP. String is an example of Reference data types provided by java. We will discuss it further article.

Hope you got clear idea about java datatypes.