Java Bugs - integral operations bug

Byte and short operands are always promoted to int.

Java's handling of arithmetic operations is weird. The rule is that all integral expressions are evaluated at 32 bits, or 64 bits if one of the operands is a long. If you want a short or byte results, you cast it back to extract the low order bits.

This sample program demonstrates how absurd this rule is. It means you have to use parentheses and a cast for a simple short=short+short or byte=byte+byte expression. The issues for me are clarity of expression and the principle of least astonishment. Java should let you write clear code, and should do what a reasonable programmer expects it to. The current arithmetic promotion model fails on both counts.

What it needs to do instead is promote to the largest involved type, as is already done with ints vs. longs. Since that's already in the language I don't think you can argue that it's too complicated to put into the language. The implementation would be different, of course.

This bug is still present in JDK 1.1.

View the source code.

% javac Incompatible type for =. Explicit cast needed to convert int to short.
        s = s1 + s2;
          ^ Incompatible type for =. Explicit cast needed to convert int to byte.
        b = b1 + b2;
2 errors

Back to bugs.
Back to ACME Java.
Back to ACME Labs.