Mixing Integer Types in Expressions
You'll learn: How Java automatically handles different integer types when you combine them in calculations.
Why Integer Types Need Rules for Mixing
When you write an expression like byte + short, Java needs to decide what type the result should be. Since byte holds values from -128 to 127 and short from -32,768 to 32,767, what happens when you add them together?
Automatic Promotion to int
Java follows a simple rule: any arithmetic operation involving integer types smaller than int automatically promotes them to int. This means when you mix byte, short, or even two byte values, Java converts them all to int first, then performs the calculation.
byte a = 10;
byte b = 20;
// byte result = a + b; // ERROR! a + b produces an int
int result = a + b; // Correct: result is int
Even though both operands are byte, the addition produces an int.
When long Takes Over
If any operand in the expression is long, the entire result becomes long:
int x = 100;
long y = 200L;
long result = x + y; // int x is promoted to long
Explicit Casting for Reassignment
If you need to store the result back into a smaller type, you must explicitly cast it (accepting the risk of overflow):
byte a = 10;
byte b = 20;
byte result = (byte)(a + b); // Cast required
Key Takeaway: Java promotes byte and short to int in expressions for performance and safety; if any operand is long, the result is long. You need explicit casting to assign back to smaller types.