Java Type Casting
Type casting is when you assign a value of one primitive data type to another type. In Java, this process can happen automatically or require manual intervention, depending on whether you are moving from a smaller type to a larger one, or vice-versa.
Types of Casting
There are two types of casting in Java:
1. Widening Casting (Automatic)
Converting a smaller type to a larger type size. Java handles this automatically because there is no risk of losing data.
Order: byte → short → char
→ int → long → float
→ double
2. Narrowing Casting (Manual)
Converting a larger type to a smaller size type. You must do this manually by placing the type in parentheses in front of the value. This is risky because data might be lost.
Order: double → float → long
→ int → char → short
→ byte
Click Run to execute your code
Why do we need casting?
A common scenario is calculating a percentage or average. Even if the inputs are integers, the result should likely be a decimal (double).
int maxScore = 500;
int userScore = 423;
// Problem: Integer division results in 0
double percentage = userScore / maxScore * 100.0; // Wait, this might be 0.0!
// Solution: Cast one operand to double first
double correctPercentage = (double) userScore / maxScore * 100.0;
Type Promotion in Expressions
When evaluating expressions, Java automatically promotes smaller types to larger types to perform the calculation. This can sometimes lead to compilation errors if you try to store the result back into a smaller variable.
byte,short, andcharoperands are always promoted toint.- If any operand is
long, the whole expression is promoted tolong. - If any operand is
float, the whole expression is promoted tofloat. - If any operand is
double, the whole expression is promoted todouble.
Click Run to execute your code
Summary
- Widening Casting (small → large) is automatic and safe.
- Narrowing Casting (large → small) requires manual
syntax:
(targetType) variable. - Be careful with data loss (truncation) when narrowing.
- Arithmetic expressions automatically promote types (e.g., byte + byte = int).
What's Next?
Primitive types are great, but what about text? In Java, text is handled by the String class, which is not a primitive type but a powerful object. Let's explore Strings in the next lesson.
Enjoying these tutorials?