In Java is boolean cast useless?

I see that the explicit cast syntax for boolean (boolean) is syntactically legal, but I can't think of a use for it. The corresponding Boolean object -- or rather casting back and forth between boolean and Boolean -- is handled by autoboxing. So it seems like a useless language artifact of the compiler. Is there a functional scenario I am missing?


It can make a difference when an overloaded method is called. Since the method to call is determined by the static type(s) of the parameter(s) (See JLS, §15.12.2), casting a Boolean to a boolean or vice-versa can change which method is called:

class Ideone {
    public static void main (String[] args) {
        final Boolean b = true;
        foo((boolean) b); // prints out "primitive"
        foo(b);           // prints out "wrapper"
 
    }
 
    public static void foo(boolean b) {
        System.out.println("primitive");
    }
 
    public static void foo(Boolean b) {
        System.out.println("wrapper");
    }
}

Ideone Demo

Notice that when casting from Boolean to boolean, a NullPointerException may occur when the Boolean has a value of null.

Whether this behaviour is (extensively) used or should be used is another debate, however.

rzwitserloot showed another case with boolean and Object in their answer. While rzwisterloot's case seems similar, the underlying mechanism is different since the downcast from Object to boolean is defined separately in the JLS. Furthermore, it is prone to a ClassCastException (if the Object is not a Boolean) aswell as a NullPointerException (if the Object is null).


Not entirely.

Ordinarily, applying the cast operator with a primitive type serves only one purpose, which is to convert one primitive type to another. boolean is the only primitive type with the property that nothing can be converted to a boolean, and a boolean cannot be converted to anything else.

But, there is a second purpose to these, although it's not exactly spelled out in the JLS and is a dubious code style practice: It effectively causes auto-unboxing to trigger. And it even combines the job of triggering auto-unbox and an ordinary type cast:

Object o = true;
boolean b = (boolean) o;
o = "Hello";
b = (boolean) o;

compiles just fine. It'll cause a ClassCastException on the 4th line, as expected. Without the boolean cast, you'd have to do something like:

boolean b = ((Boolean) o).booleanValue();

which is definitely more wordy. Exactly how often you end up wanting to cast some expression of type Object to boolean - probably that's a very rare occurrence, but it is a real one, and disallowing (boolean) would have made the JLS longer, not shorter (and the javac codebase wouldn't be any shorter either).