posted 18 years ago
Hi,
Welcome to JavaRanch!
The compound assignment operators effectively include a cast to the appropriate type -- i.e.,
b += 10;
is actually not equivalent to
b = b + 10;
but rather
b = (byte) (b + 10);
So this explains line 2. Line 4 compiles because " 'b' + 1" is a constant expression which can be evaluated at compile time; the compiler can see that it is less than Byte.MAX_VALUE so there is no overflow, and the result is a byte constant.
Line 3, on the other hand, is evaluated at runtime. The compiler doesn't keep track of the values of variables on previous lines of code, so as far as it knows, the expression might overflow; therefore, this is an error.