TwoThe TwoThe - 1 year ago 77
Java Question

Is this valid Java language?

I stumbled upon an old Java code during work that was implemented years ago by a C programmer, and we couldn't help but do start a discussion whether or not the code - even though it compiles and works - is actually valid Java code.

final Object o = Boolean.TRUE;
boolean b = (boolean) o;

This is essentially the code in question. As you can see there is a not so nice cast from Object to primitive boolean, which shouldn't be possible, but happens to work, thanks to some implicit boxing magic.

If I do the following

final Object o = Boolean.TRUE;
if (o instanceof Boolean) {
b = (boolean) o;

I even get a warning at the line where o is cast to b saying "Cast is incompatible with given instanceof". Which is obviously true but then still works because of the implicit boxing.

Now the question is: is that cast actually allowed by the Java specification and therefore should work with future JVM versions? Or does it just happen to work in the current version and might no longer work in a future JVM update?

Answer Source

This is defined in JLS 8, section 5.5. It specifically allows casting with unboxing conversion from Object to a primitive type (see also table 5.5-A). Specifically the JLS says:

An expression of a reference type may undergo casting conversion to a primitive type without error, by unboxing conversion.

See my answer to a similar question for more details: Differences in auto-unboxing between Java 6 vs Java 7

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download