4

My ternary operator is throwing a NullPointerException even though I explicitly check if the value of my list is null. However, if I add parenthesis around the ternary operator, my code works.

Code without parenthesis (throwing the exception):

final List<String> listData = null;
System.out.println("Insert new data (Created Monitorings) : " + 
        listData != null ? listData.size() : 0);

Code with parenthesis (working fine):

final List<String> listData = null;
System.out.println("Insert new data (Created Monitorings) : " + 
        (listData != null ? listData.size() : 0));

Can somebody explain it how exactly it is working.

Ivar
  • 6,138
  • 12
  • 49
  • 61

3 Answers3

8

This is about precedence of operators: the String+ has a much higher precedence than following ternary operator.

Therefore your first snippet actually does this:

( "Insert new data (Created Monitorings) : " + listData ) != null 
  ? listData.size() : 0

Meaning: you concat a string (with a null listData), and compare that against null. Obviously that concat'ed string isn't null. Thus you do call listData.size(). And that resembles to null.size() which leads to your NullPointerException.

You are comparing the wrong thing against null! In the second snippet the ( parenthesises ) ensure that the result of ternary operation gets added to your string.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

in snippet one the value that is compared to null is "Insert new data (Created Monitorings) : " + listData

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

'+' has more precedence than '!='

Hence Snippet 1 translates to:

(("Insert new data (Created Monitorings) : " + listData) != null ? listData.size() : 0;

The expression is not null so it proceeds to listData.size(). But as it is null, it throws the exception.