Casting in Java is the process of converting a variable from one type to another. This can involve both primitive types and reference types. Casting is essential when you need to interact with different types of data, especially when dealing with inheritance and interfaces.
There are two main types of casting in Java:
Primitive type casting involves converting one primitive data type into another. There are two kinds of primitive type casting:
This happens automatically when converting a smaller type to a larger type. For example, byte to int or int to double. This is safe because there is no loss of information.
int num = 100;
double d = num; // Implicit casting: int to double
System.out.println(d); // Output: 100.0
This requires explicit syntax to convert a larger type to a smaller type, as it can result in data loss.
double d = 100.04;
int num = (int) d; // Explicit casting: double to int
System.out.println(num); // Output: 100
Reference type casting is used with objects and can be categorized as: