In Java is boolean cast useless?

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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)