Type Casting in Java
Type Casting in Java
In Java, type casting is a method or process that converts a data type into another data
type in both ways manually and automatically. The automatic conversion is done by the
compiler and manual conversion performed by the programmer. In this section,
Type casting
Convert a value from one data type to another data type is known as type casting.
1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
Let's see an example.
WideningTypeCastingExample.java
Output
In the above example, we have taken a variable x and converted it into a long type. After
that, the long type is converted into the float type.
1. double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times.
First, we have converted the double type into long data type after that long data type is
converted into int type.
NarrowingTypeCastingExample.java
Output