views:

157

answers:

4

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?

+10  A: 

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

Jon Skeet
That's because a primitive type can **never** be null.
The Elite Gentleman
@The Elite Gentleman Thats what I mentioned
org.life.java
@org.life.java, sorry, never read your post....
The Elite Gentleman
@The Elite Gentleman :) :)
org.life.java
+8  A: 

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

org.life.java
It's not really anything to do with default values. It's to do with the fact that primitive types are value types - the value of an `int` variable is the integer itself, not a reference... so how could it ever be `null`?
Jon Skeet
@Jon, I mentioned about default value just to make OP understand that in any case primitive won't hold NULL
org.life.java
@org.life.java: To me, that confuses things more than making them clearer. The difference between value types and reference types has very little to do with default values.
Jon Skeet
@Jon I too realized that after reading your comment, Updated answer.
org.life.java
+3  A: 

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.

Teja Kantamneni
+2  A: 

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.

David Zimmerman