1

I have function foo() that returns true/false/null.

I have this piece of code:

Boolean flag = foo();
if (flag != null){
.....
}

When inspecting the if statement, I get the following exception: java.lang.NullPointerException at booleanValue()

Seems that it tries to evaluate its primitive value and compare it . However, this is what I do NOT want it to do. I want to check whether it is initialized...

Any ideas?

Thanks

4
  • 1
    The code you've shown should be fine - I suspect your problem lies elsewhere. Please show a short but complete program which demonstrates the problem. Alternatively, it may be to do with how you're performing the "inspection". Does the code run as you expect it to? Is this just a debugger issue? If so, how are you debugging and in which debugger? Commented Jun 22, 2010 at 6:24
  • Are you sure about that? Please post the actual code (with line numbers!) and the actual exception stacktrace. Commented Jun 22, 2010 at 6:26
  • Definitely not using != false? How are you inspecting the statement? Your debugger might be converting it to a bool when you inspect. Commented Jun 22, 2010 at 7:02
  • In line with graphain's comment and because the name booleanValue() doesn't appear in your code, could it relate to this debugger method: java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/com/sun/jdi/… Commented Jun 23, 2010 at 1:28

2 Answers 2

3
    Boolean flag = null;
    if (flag != null){
        System.out.println("BLuh");
    }

This code runs fine - so the problem is defenetly elsewhere.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you guys, Ther simple code Boolean flag = null; if ( flag!=null) ... else ... Works for me too. It is quite strange but I have figured out a workaroung. When I'll have time I'll get back to it and post and solution here. Thanks :)
2

The error indicates that something like this happens:

Boolean iAmNothing = null;
boolean crash = iAmNothing.booleanValue(); // throws NPE

or with outboxing (Java 1.5+):

Boolean iAmNothing = null;
boolean crash = iAmNothing;                // throws NPE

The code snippet shows none of these problems, so the NPE either occurs elsewhere inside the block behind the if statement or maybe you're not using the SUN jdk but a different one with different behaviour !?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.