Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening and Narrowing.
int by a float). Type casting tells Java how to handle these conversions safely.
Widening casting happens when you pass a smaller type to a larger type size. It is done **automatically** by the Java compiler because there is no risk of losing data.
The hierarchy of widening casting is as follows:
byte -> short -> char -> int -> long -> float -> double
In the example above, the integer 9 is automatically converted to the double 9.0 because a double (8 bytes) is larger than an int (4 bytes).
Narrowing casting happens when you pass a larger type to a smaller size type. This must be done **manually** by placing the type in parentheses () in front of the value.
Note: Narrowing casting can result in "Data Loss" because the smaller type might not be able to hold the full value of the larger type.
double -> float -> long -> int -> char -> short -> byte
Type casting is very useful when you have integer data but you need a precise decimal result.
What happens if you cast a number that is too big for the target type? Java will perform a "wrap-around". For example, a byte can only hold values up to 127. If you cast 130 to a byte, you will get a unexpected negative number.
byte or short.
When you perform arithmetic operations, Java automatically promotes the operands to a common type:
double, the whole expression is promoted to double.float, the whole expression is promoted to float.long, the whole expression is promoted to long.int.| Feature | Widening (Implicit) | Narrowing (Explicit) |
|---|---|---|
| Conversion | Small to Large | Large to Small |
| Effort | Automatic by Compiler | Manual by Programmer |
| Data Loss | No risk of loss | High risk of loss |
| Memory | Grows | Shrinks |
Type casting is an essential tool for every Java developer. It allows you to control how data flows between different types of variables. Now that you know how to convert data, it's time to learn how to manipulate it! In the next chapter, we will explore Java Operators.
Next: Java Operators →