2

Can anybody explain how is it possible that I am getting null pointer exception thrown from this line of code:

if (data != null && data.isActive()) {

Body of method isActive() is just:

public Boolean isActive() 
{
  return active;
}

Thanks in advance.

14
  • 1
    is it possible that the NPE is thrown within or by method()? Commented May 5, 2015 at 14:09
  • 6
    Edit your question and add method() source Commented May 5, 2015 at 14:10
  • 1
    data may not be null, but method() might be throwing a NPE. post the method() code. Commented May 5, 2015 at 14:11
  • 2
    Does your isActive method returns boolean and active is Boolean (wrapper)? Commented May 5, 2015 at 14:13
  • 5
    your active variable is null, and java gets NPE when tries to unbox null value Commented May 5, 2015 at 14:15

1 Answer 1

13

In java, there's a thing called autoboxing, when primitive values are wrapped by object types and vice versa.

So, in your code there is a method:

public Boolean isActive() 
{
  return active;
}

note, that you are returning Boolean (object type), not boolean (primitive type).

and return value is going to be used in your if statement.

if (data != null && data.isActive()) {

when java meets data.isActive() in your if statement, it tries to convert Boolean value to primitive boolean value, to apply it for your logical operation.

But your active variable inside of your isActive() method is null, so java is unable to unbox this variable to boolean primitive value, and you get Null pointer exception.

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

1 Comment

whoever downvote my answer, please leave a comment, to let me know, what is wrong with my assumptions. Thank you.

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.