What Is Type Casting?
Type casting in Java means converting a value from one data type to
another. For example, converting a whole number (int) into a decimal number
(double).
Types of Type Casting in Java
Java supports two kinds of type casting:
1 .Widening Casting (Automatic Conversion)
Widening casting happens automatically when you convert a smaller data
type into a larger one.
Order of widening conversion:
byte → short → char → int → long → float → double
Since larger types can store all values of smaller types, no data is
lost.
Example: Widening Casting
int distance = 120;
double totalDistance = distance;
System.out.println(distance); // 120
System.out.println(totalDistance); // 120.0
Java automatically converts int to double.
2 .Narrowing Casting (Manual Conversion)
Narrowing casting is required when converting a larger data type into a
smaller one. This must be done manually using parentheses, because some
data (like decimals) may be lost.
Order of narrowing conversion:
double → float → long → int → char → short → byte
Example: Narrowing Casting
double temperature = 36.7;
int roundedTemp = (int) temperature;
System.out.println(temperature); // 36.7
System.out.println(roundedTemp); // 36
The decimal part is removed during conversion.
Why Narrowing Casting Is Risky
When narrowing:
- Decimal values may be truncated
- Large numbers may overflow
- Data accuracy can be reduced
That’s why Java forces you to cast manually, so you’re aware of the
risk.
Real-World Example: Exam Percentage Calculation
In this example, we calculate a student’s percentage score. Type casting
is used to ensure accurate decimal results.
Example Program
// Total marks possible
int totalMarks = 600;
// Marks obtained by the student
int marksScored = 487;
// Convert marksScored to double for accurate calculation
double resultPercentage = (double) marksScored / totalMarks *
100;
System.out.println("Student percentage: " +
resultPercentage);
Why Casting Is Needed Here?
If both values were int, Java would perform integer division, which removes
decimals. Casting ensures the result is calculated using floating-point
arithmetic.