Why second line throws ClassCastException in runtime?
Object obj = new Integer(2);
Byte b2 = (byte) obj; // at Runtime: ClassCastException "Integer cannot be cast to Byte"
I thought that Integer (to which reference obj points) is unboxed into int, then cast to byte, then boxed into Byte and successfully assigned. Eclipse compiler warning also says that (correcting me just a bit):
- The expression of type Object is unboxed into byte
- The expression of type byte is boxed into Byte
So why it cannot assign this Byte in RHS into Byte reference in LHS?
P.S. Same ClassCastException on Oracle javac compiler
If Object obj = new Integer(2);, then Long b2 = (long) obj; works but Long b2 = 7; fails. While Byte b2 = (byte) obj; fails, but Byte b2 = 7; is fine! Maybe there some clue in those reciprocal differences?
Empirically, I would say that narrowing of primitive type is prohibited (even with explicit cast) after unboxing (while widening is allowed) - it could explain this behavour.
Got it finally:
5.2. Assignment Contexts (JLS): variable = expression
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
Byte and the value of the constant expression is representable in the type byte.
Short and the value of the constant expression is representable in the type short.
Character and the value of the constant expression is representable in the type char.
But this is also fine in Runtime:
Object o = new Integer(2);
Integer i2 = (Integer) o;
Integer i3 = (int) o;
We need to further expore "assignment context" vs "assignment context" - how they work together.