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.

luke
  • 3,531
  • 1
  • 26
  • 46

1 Answers1

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.

  • 7
    whoever downvote my answer, please leave a comment, to let me know, what is wrong with my assumptions. Thank you. –  May 05 '15 at 14:22