Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting NullPointerException in my ternary operator?

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.

like image 822
Pramendra Raghuwanshi Avatar asked Jan 01 '23 23:01

Pramendra Raghuwanshi


1 Answers

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.

like image 81
GhostCat Avatar answered Jan 08 '23 03:01

GhostCat