Java - Type Casting
The type casting is a method of converting the value of one data type to another data type. It is also known as type conversion. In Java, there are several kinds of conversions. However, in this tutorial we will focus only on two major types.
- Widening Type Casting
- Narrowing Type Casting
To learn more about other types of conversion in Java, please visit Conversions and Contexts (official Java documentation).
Widening Type Casting
The widening type casting (widening conversion) happens automatically when converting a smaller data types to larger data types. The compiler implicitly typecast the smaller data types to the larger data types. No data will be lost in this process.
Example
The example below shows how the widening conversion is done in Java.
public class MyClass { public static void main(String[] args) { byte num_byte = 10; //Widening Casting short num_short = num_byte; int num_int = num_short; long num_long = num_int; float num_float = num_long; double num_double = num_float; //printing variables System.out.println("num_byte = " + num_byte); System.out.println("num_short = " + num_short); System.out.println("num_int = " + num_int); System.out.println("num_long = " + num_long); System.out.println("num_float = " + num_float); System.out.println("num_double = " + num_double); } }
The output of the above code will be:
num_byte = 10 num_short = 10 num_int = 10 num_long = 10 num_float = 10.0 num_double = 10.0
Narrowing Type Casting
The narrowing type casting (narrowing conversion) does not happen automatically. It is performed manually by calling the compiler explicitly to typecast the larger data types into the smaller data types. There might be a data loss in this process.
Example
The example below shows how the perform narrowing conversion by calling the compiler explicitly.
public class MyClass { public static void main(String[] args) { double num_double = 10.5d; //Narrowing Casting float num_float = (float) num_double; long num_long = (long) num_float; int num_int = (int) num_long; short num_short = (short) num_int; byte num_byte = (byte) num_short; //printing variables System.out.println("num_double = " + num_double); System.out.println("num_float = " + num_float); System.out.println("num_long = " + num_long); System.out.println("num_int = " + num_int); System.out.println("num_short = " + num_short); System.out.println("num_byte = " + num_byte); } }
The output of the above code will be:
num_double = 10.5 num_float = 10.5 num_long = 10 num_int = 10 num_short = 10 num_byte = 10