// IntOpBug // // 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 as of JDK 1.1. package Bugs; public class IntOpBug { public void foo() { int i1 = 1, i2 = 2, i; long l1 = 1, l2 = 2, l; short s1 = 1, s2 = 2, s; byte b1 = 1, b2 = 2, b; // These work ok. i = i1 + i2; l = l1 + l2; // These get a *compile* error! "Incompatible type for =. Explicit // cast needed to convert int to {short,byte}." Same thing happens // with other operations besides plus. s = s1 + s2; b = b1 + b2; // Here's what you have to use instead. s = (short) ( s1 + s2 ); b = (byte) ( b1 + b2 ); } }