📦 Variables & Types · Beginner

Numeric promotion in expressions in Java

byte/short/char promote to int in arithmetic; mixed types promote to the wider type.

🧩 The mysterybyte 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.

🔮 Predict it

Your turn

Two shorts, 1 + 2. What happens?

short x = 1;
short y = 2;
short z = x + y;
System.out.println(z);
  1. 3
  2. Compile error
  3. 12
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.5

One 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.

🔮 Predict it

Your turn

What does this print?

System.out.println(7 / 2 * 2.0);
  1. 7.0
  2. 6.0
  3. 6
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.

⚠️ The trap

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)); // B
💼 In the real world

In 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

  1. byte + byte is an int
  2. int + long → long; anything + double → double
  3. Promotion happens per operation, left to right
🤯 Did you know?

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;
  1. int
  2. short
  3. byte
  4. 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);
  1. 30
  2. Throws ArithmeticException
  3. Compile error
  4. 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);

Next: char is secretly a number. And some emoji are secretly two chars. Let's look inside.