Section 2: Explicit TypeCasting

This is also called Narrowing casting or Downcasting. This is not automatically done by the compiler, the programmer manually needs to cast from upper type to lower data type.

Explicit typecasting follows the following order:

Type Casting in Java

Programmer needs to explicitly add () and convert into any type. If not added then compile will give a compile-time error.

Example for Explicit type casting:

Type Casting in Java

In the above example, we are adding (byte) explicitly to avoid a compile-time error and typecast int into a byte.

If we try to convert a higher number int value into byte value (value greater than byte-range) then we will not get the same number after converting into the byte since while converting it into byte value, it will convert that number which is in between the byte range. As shown in the following example.

Type Casting in Java

Similarly, if we try to convert the double value into int then we will lose the digits after the decimal place. As shown in the following example.

Type Casting in Java

In the above example, we lost data “.345” after digit. So in the case of Explicit typecasting, we have chances of data loss.

-A blog by Shwetali Khambe

Related Posts