Data types in java

Previous
Next

Data types in java  refer to type of data that can be stored in variable. As Java is strongly typed language, you need to define datatype of variable to use it and you can not assign incompatible datatype otherwise the compiler will give you an error.

The compiler will give you an error with this message – “Type mismatch: cannot convert from String to int”.
There are two types of data types in java.

  • Primitive data types
  • Referenced data types.

Primitive data types:

Primitive data types are those datatypes which are defined by java language itself.

There are 8 primitive data types in java.

Data Type Default Value Default size
boolean false 1 bit
char ‘\u0000’ 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Let’s see some example about data types:

Adding two integers:

When you run above program, you will get below output:

30

Assigning int to double(Widening):

Here we will assign int to double. As double takes more memory than int. This is widening operation.

When you run above program, you will get below output:

30
30.0

Assigning double to int(Narrowing or typecasting):

Here we will assign double to int. As double takes more memory than int. This is Narrowing operation.

When you run above program, you will get below output:

30.0
30

Assinging int to byte(Overflow condition):

When you assing int to byte and value of int is larger than size of byte then it is a case of overflow.

When you run above program, you will get below output:

200
-56

Reference data types:

Reference data types are those data types which are provided as class by Java API or by class that you create.
String is example of Reference data types provided by java.

That’s all about data types in java.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog