Type conversion in java

  • by

Type conversion means assigning one type of data to another type of variable.

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

1) The two types are compatible:
For automatic conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.

2) The destination type is larger than the source type:
We all know variables are nothing but the container which holds the data. each variable has it’s own storage capacity. for understanding purpose byte,short,int,long are considered as glass (container) with different storage capacity which is shown below. when you try assign byte value into int type of variable means you are pouring the content of byte glass into int glass which is perfectly possible because capacity of int is higher than the byte. what happens when you try to assign lower data type variable to higher data type variable, compiler first converts the data of lower data type  to higher data type and then assign to higher data type variable which is nothing but the automatic type conversion.

Compatibility table with respective of destination and source data type is given below:

Example of automatic conversion given below:
byte b=20;
int a=b;
Auto conversion for above example is possible because byte and int  are compatible with each and destination type i.e int is higher source type i.e byte.