1

I'm getting nullpointer exception if I use ternary operator.

Integer val = null;
Object res = val == null ? val : val.intValue();

But not with if else

    Integer val = null;
    Object res;
  if( val == null ) {
      res  = val;
  } else {
      res = val.intValue();
  }

Can anyone please explain why?

Thanks Sudar

lospejos
  • 1,976
  • 3
  • 19
  • 35
Sudarsana Kasireddy
  • 922
  • 1
  • 8
  • 24

1 Answers1

5

The behavior you encountered results from the rules of determining the type of the ternary conditional expression.

In your case, the type of the expression

val == null ? val : val.intValue();

is int.

This is specified by JLS 15.25. :

The type of a conditional expression is determined as follows:

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.

  • If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

Your second operand is Integer and your third operand is int, therefore the type of the expression is int.

Therefore, when val == null, val is un-boxed (i.e. val.intValue() is called for a null value) and a NullPointerException is thrown.

In your if-else expression val is not un-boxed when its value is null (since you assign it to an Object variable, so there's no NullPointerException.

That said, since you are assigning an Integer variable to an Object variable, your conditions in either of the snippets are pointless (since assigning an int to an Object variable simply boxes the int back to Integer).

You can simply assign

Object res = val;

and get the same end result without the exception.

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks for quick response Eran. I tried to assign Integer object in third argument, it assigns null without throwing null pointer exception . Integer y = null; Object res = val == null ? val : y; – Sudarsana Kasireddy Dec 26 '16 at 13:53