Implicitly Typecasting in Java
The process of converting one type of object and variable into another type is referred to as Typecasting. When the conversion automatically performs by the compiler without the programmer's interference, it is called implicit type casting or widening casting.
In implicit typecasting, the conversion involves a smaller data type to the larger type size. For example, the byte datatype implicitly typecast into short, char, int, long, float, and double. The process of converting the lower data type to that of a higher data type is referred to as Widening.
In the same expression, when two different types of variables are involved:
- The Java compiler uses the predefined library function for transforming the variables.
- The conversion of variables is done into a common datatype.
- After that, the expression is executed.
There are certain rules which are used by the compiler to determine which variable's datatype needs to be converted. The rules which are followed by the compiler are as follows:
- The double is a higher data type, so if any of the variables are of type double, the other variable's data type will be promoted into double.
- The float is the second-highest data type, so if in both variable's datatype no one is of type double and one should be of type float, the other variable's datatype will be promoted into the float.
- The long is the third-highest datatype, so if both the variable's data types neither double nor float and one of them is long, the other will be promoted into long.
- If in both of the datatypes int is highest one, the other will be promoted into the int.
- If neither the variable's data type is double, float, long or int, both variable's datatypes will be promoted into the int.
The automatic type conversion is possible of one type of numeric data type into other types. The automatic conversion from numeric to char or Boolean is not possible or can say not compatible.
Let's take an example to understand how implicit typecasting is done in Java:
In the above code, we have taken a variable p of type byte and initialized 12 into it. We then use the print statement to print the value of p. We perform the implicit typecasting by passing the value of a variable into a different type of variable.
- We pass the value of variable p to variable q that is of type short. In this case, the byte data type is promoted into the short data type.
- We pass the value of variable q to variable r that is of type int. In this case, the short data type is promoted into the int data type.
- We pass the value of variable r to variable s that is of type long. In this case, the int data type is promoted into a long data type.
- We pass the value of variable s to variable t that is of type float. In this case, the long data type is promoted into the float data type.
- We pass the value of variable t to variable u that is of type double. In this case, the float data type is promoted into the double data type.