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?