← Back to Chapters

Java Type Promotion

? Java Type Promotion

? Quick Overview

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.

? Key Concepts

  • Applies mainly to arithmetic expressions
  • byte, short, and char are promoted to int
  • If one operand is long, float, or double, result follows the higher type
  • Happens automatically at compile time

? Syntax / Theory

Java follows a fixed promotion order when evaluating expressions:

byte → short → int → long → float → double

? Code Example

? View Code Example
// 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);
}
}

? Output / Explanation

Although a and b are bytes, Java promotes them to int before addition. Hence, the result must be stored in an int variable.

? Another Example

? View Code Example
// 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);
}
}

? Output / Explanation

Here, int is promoted to double before addition. The final result is a double value.

✅ Tips & Best Practices

  • Always store arithmetic results in appropriate larger data types
  • Be careful when assigning promoted results back to smaller types
  • Use explicit casting when required

? Try It Yourself

  • Add a char and an int and observe the result
  • Try multiplying float and long
  • Experiment with explicit casting after promotion