Casting boolean to Boolean in java – Education Career Blog

i have a code as

public class BooleanTest {
    public BooleanTest() {
        super();
    }


    public static void main(String args){
      BooleanTest bt = new BooleanTest();
      bt.doProcess();

    }

    private boolean method() {
        return false;
    }

    private void doProcess() {
      Boolean obj = (Boolean)method();
      System.out.println(obj.booleanValue());
    }
}

the question is can line System.out.println(obj.booleanValue()); throw NullPointerException in any situation?

,

No, when you box a primitive value into its equivalent wrapper type, the result is never null.

,

No,

Reason: primitive never hold null so converting them to Wrapper will never lead to NPE,

And also no need to caste it will autobox

,

It will never throw a NPE and also if you are using java >= 1.5, you don’t need to cast it. It is called autoboxing which is introduced from JDK 1.5.

,

Just to be pedantic, you might have set System.out to be null, then that line will generate an NPE.

But that would be odd.

Leave a Comment