11

I written short Java code which cause NullPointerException. Does anybody have explanation for this? Code:

int val = 2;
Boolean result = (val == 0) ? false : ((val == 1) ? true : null);

Also following (simplified version) code will cause NullPointerException:

Object result = (false) ? false : (false ? true : null);

But this:

int val = 2;
Boolean result = (val == 0) ? Boolean.FALSE : ((val == 1) ? true : null);

and this:

Object result = (false) ? Boolean.FALSE : (false ? true : null);

or this:

Object result = (false) ? (Boolean)false : (false ? true: null);

doesn't?

Jokii
  • 309
  • 2
  • 6

3 Answers3

4

I think what's happening is that ((val == 1) ? true : null) always returns null and it then tries to unbox that into a boolean. That causes a null pointer exception.

After I said this, @JonSkeet marked your question as a duplicate because of NullPointerException in ternary expression with null Long The answer there has a much more detailed explanation.

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
0

int val = 2;

boolean result = (val==o)? false:true; // remove null from code and replace it with true.

Nash
  • 131
  • 1
  • 4
  • 17
-1

In java, boolean allows only true and false but Boolean allows true false and NULL

noMAD
  • 7,744
  • 19
  • 56
  • 94