Assigning a value of one primitive data type to another primitive data type is known as casting. There are two types of type casting in java as shown in the following diagram.
- Narrowing(explicit) type casting
- Widening(implicit) type casting
Narrowing Type Casting
It is also known as explicit type casting. It is done when assigning a larger size data type to smaller size data type, thus the term narrowing is used.
Notice the int
inside parentheses before double variable d
and float variable f
. This is done when passing the larger size data type value to smaller size data type.
public class JavaExample { public static void main(String[] args) { double d = 4.55d; float f = 1.25f; int i = (int)d; // Explicit casting: double to int int i2 = (int)f; // Explicit casting: float to int System.out.println("Double Value: "+d); // Prints 4.55 System.out.println("Double to int: "+i); // Prints 4 System.out.println("Float value: "+f); // Prints 1.25 System.out.println("Float to int: "+i2); // Prints 1 } }
Output:
Widening Type Casting
Widening type casting is an automatic casting. In this type casting, a value of smaller data type is assigned to larger size data type. This is also called implicit type casting as there is no need to mention the data type in parentheses and the conversion is handled automatically by the compiler.
public class JavaExample { public static void main(String[] args) { int i = 1001; float f = 105.00f; long l = i; // Implicit casting: int to long double d = f; // Implicit casting: float to double System.out.println("int Value: "+i); // Prints 1001 System.out.println("int to long: "+l); // Prints 1001 System.out.println("float value: "+f); // Prints 105.0 System.out.println("float to double: "+d); // Prints 105.0 } }
Output: