Why I am getting NullPointerException in my ternary operator?

Pramendra Raghuwanshi :

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.

GhostCat salutes Monica C. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72735&siteId=1