views:

60

answers:

1

Thanks to the implicit casting in compound assignments and increment/decrement operators, the following compiles:

byte b = 0;
++b; b++; --b; b--;
b += b -= b *= b /= b %= b;
b <<= b >>= b >>>= b;
b |= b &= b ^= b;

And thanks to auto-boxing and auto-unboxing, the following also compiles:

Integer ii = 0;
++ii; ii++; --ii; ii--;
ii += ii -= ii *= ii /= ii %= ii;
ii <<= ii >>= ii >>>= ii;
ii |= ii &= ii ^= ii;

And yet, the last line in the following snippet gives compile-time error:

Byte bb = 0;
++bb; bb++; --bb; bb--; // ... okay so far!
bb += bb; // DOESN'T COMPILE!!!
// "The operator += is undefined for the argument type(s) Byte, byte"

Can anyone help me figure out what's going on here? The byte b version compiles just fine, so shouldn't Byte bb just follow suit and do the appropriate boxing and unboxing as necessary to accommodate?


Extra question

So is there a way to make compound assignment operators work with Byte, Character, and Short on the left hand side, or are they simply illegal(!!!) for these types?

+5  A: 

Section § 5.1.7 (Boxing) of the standard says:

From type boolean to type Boolean
From type byte to type Byte
From type char to type Character
From type short to type Short
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double

Note there is no int to Byte. When you do bb + bb it's converted to int + int, which isn't boxed back to Byte. For the byte version, int + int is cast back to byte directly (narrowing primitive conversions, § 5.1.3) so it's allowed.

JRL
I'd think that since there's `int` to `byte`, and there's `byte` to `Byte`, the compiler would figure out that there's a valid path from `int` to `Byte` after all! Apparently this is not the case? Is there a way to make the compound assignment work with an explicit cast perhaps?
polygenelubricants
Well obviously this would work `bb = Byte.valueOf((byte)(bb + bb))`, but aside from that I don't know.
JRL