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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With