Type Casting is assigning a value of one data-type to a variable of another data-type.
When a value is assigned to another variable, their types might not be compatible with each other to store that value. For this situation, they need to be cast or converted explicitly. But if they are compatible then java converts the values automatically which is known as Automatic Type Conversion.
In Java, there are two types of casting:
- Widening Casting (Implicit)
- Narrowing Casting (Explicitly)
1. Widening Casting (Implicit):
Converting a data-type of smaller size to a type of larger size. It is also known as Automatic Type Conversion.
byte -> short -> char -> int -> long -> float -> double
Example of Widening or Implicit Casting:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class WideCast { public static void main(String[] args) { int i = 10; long l = i; //converted automatically float f = l; //converted automatically System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); } } |
Output:
1 2 3 | Int value 10 Long value 10 Float value 10.0 |
2. Narrowing Casting (Explicit):
Converting a data-type of larger size (occupying larger space) to a type of smaller size. For this type of conversion programmer itself to perform the task. Here, unlike Widening Casting, JVM(Java Virtual Machine) does not take part.
double -> float -> long -> int -> char -> short -> byte
Example of Narrowing or Explicit Casting:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class NarrowCast { public static void main(String[] args) { double d = 200.04; long l = (long)d; //converted manually int i = (int)l; //converted manually System.out.println("Double value "+d); System.out.println("Long value "+l); System.out.println("Int value "+i); } } |
Output:
1 2 3 | Double value 200.04 Long value 200 Int value 200 |