Is casting from Object to boolean valid Java language?
Asked Answered
M

2

14

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?

Mizuki answered 23/11, 2016 at 17:43 Comment(1)
Related: #16120138Woody
W
8

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

Woody answered 23/11, 2016 at 17:51 Comment(0)
R
8

Yes. It is legal. See JLS-5.1.8. Unboxing Conversion which says (in part)

Unboxing conversion converts expressions of reference type to corresponding expressions of primitive type. Specifically, the following eight conversions are called the unboxing conversions:

  • From type Boolean to type boolean
Rose answered 23/11, 2016 at 17:45 Comment(2)
Excellent quote, thanks. However the cast source in question is of type Object and not Boolean.Mizuki
@Mizuki Object is a reference type. At runtime, all instances are also of type Object.Rose
W
8

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

Woody answered 23/11, 2016 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.