Numeric promotion in expressions in Java
byte/short/char promote to int in arithmetic; mixed types promote to the wider type.
byte a = 10, b = 20; byte sum = a + b; 30 obviously fits in a byte. So why does Java refuse to compile it?Rule 1: small types become int
Before any arithmetic, byte, short and char operands are promoted to int. Java never does math in byte or short. So byte + byte is an int.
Your turn
Two shorts, 1 + 2. What happens?
short x = 1;
short y = 2;
short z = x + y;
System.out.println(z);3Compile error12
Show the answer
Compile error. x + y is an int expression, and int → short is narrowing, which needs a cast: short z = (short) (x + y);. The compiler checks types, not values, so it doesn't matter that 3 fits.
Rule 2: mixed types go wider
If two operands have different types, the narrower one is promoted to the wider one (int → long → float → double), and the result has that type.
3 * 2L // long: 6
5 + 1.5 // double: 6.5
10 / 4.0 // double: 2.5One operation at a time
Promotion happens per operation, left to right, not once for the whole expression. An int division that comes first stays an int division, even if a double shows up later.
Your turn
What does this print?
System.out.println(7 / 2 * 2.0);7.06.06
Show the answer
Left to right: 7 / 2 is int division, 3. Only then does 3 meet 2.0, get promoted, and give 6.0.
char math gives numbers
c is promoted to the int 65, so c + 1 is the int 66, not the letter B. Cast back to char to get a character.
char c = 'A';
System.out.println(c + 1); // 66
System.out.println((char) (c + 1)); // BIn real projects
Averages are a classic bug: double avg = total / count; with int total and count divides in int first and silently drops the decimals. Promote early: (double) total / count.
Key takeaways
- byte + byte is an int
- int + long → long; anything + double → double
- Promotion happens per operation, left to right
The JVM has no instructions for adding bytes or shorts at all: its arithmetic instructions work on int, long, float and double. Promoting small types to int matches how the machine works.
Practice questions
Which type makes this line compile with no cast?
___ result = 3 * 2L;- int
- short
- byte
- long
Check your answer
long. 3 is an int and 2L is a long, so 3 is promoted and the result is a long. Storing it in an int would need a cast.
What does this print?
byte a = 10;
byte b = 20;
byte sum = a + b;
System.out.println(sum);- 30
- Throws ArithmeticException
- Compile error
- 1020
Check your answer
Compile error. a + b has type int, and assigning an int to a byte needs a cast: byte sum = (byte) (a + b);