Type Casting in Java
2 min read ·
Type casting means converting one data type into another data type.
In Java, type casting is mainly used with numeric primitive types.
There are two types of casting:
- Widening Casting
- Narrowing Casting
Widening Casting
Widening casting is done automatically by Java.
It converts a smaller data type into a larger data type.
Order of widening:
byte → short → int → long → float → double
Example:
Output:
100
100.0
No manual casting is required because double can store int safely.
Another example:
Output:
65
Narrowing Casting
Narrowing casting must be done manually.
It converts a larger data type into a smaller data type.
Syntax:
Example:
Output:
9.78
9
Decimal part is removed.
Casting Examples
Example 1: int to long
Example 2: double to float
Example 3: long to int
Data Loss in Casting
Data loss happens in narrowing casting.
Example:
Output:
-126
Because byte range is -128 to 127.
When value exceeds the range, it overflows and gives unexpected result.
Another example:
Output:
99
Decimal value is lost.