Casting boolean to Boolean in java

I have code like

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 whether the line System.out.println(obj.booleanValue()); throw a NullPointerException in any situation?

+7
java casting boolean
source share
4 answers

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

+11
source share

No

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

And also do not need a caste , it will autobox

+7
source share

It will never throw NPE, and also if you use java> = 1.5, you do not need to throw it. It is called autoboxing, which is introduced from JDK 1.5.

+3
source share

Just to be pedantic, you could set System.out to zero, then this line will generate NPE.

But that would be strange.

+2
source share

All Articles