Type promotion in Java is the automatic conversion of smaller data types into larger data types during expression evaluation. It helps prevent data loss and ensures calculations are performed safely.
Java follows a fixed promotion order when evaluating expressions:
byte → short → int → long → float → double
// Demonstrates automatic type promotion in arithmetic expression
public class TypePromotion {
public static void main(String[] args) {
byte a = 10;
byte b = 20;
int result = a + b;
System.out.println(result);
}
}
Although a and b are bytes, Java promotes them to int before addition. Hence, the result must be stored in an int variable.
// Shows promotion when different data types are used together
public class MixedPromotion {
public static void main(String[] args) {
int x = 5;
double y = 6.5;
double sum = x + y;
System.out.println(sum);
}
}
Here, int is promoted to double before addition. The final result is a double value.
char and an int and observe the resultfloat and long