What is cast?
Casting in Java is the process of converting a variable from one data type to another. There are two main types of casting:
1. Widening Casting (Implicit Casting)
2. Narrow Casting (Explicit Casting)
1. Widening Casting (Implicit Casting)
Widening casting occurs when a smaller data type is converted into a larger data type. This is done automatically by Java, so no explicit cast is needed.
int num = 10;
double d = num; // int → double (automatic conversion)
System.out.println(d); // Output: 10.0
2. Narrow Casting (Explicit Casting)
Narrowing casting occurs when a larger data type is converted into a smaller data type. This requires explicit casting because data loss may occur.
double d = 9.78;
int num = (int) d; // double → int (explicit casting)
System.out.println(num); // Output: 9 (decimal part is truncated)