Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator and unexpected NullPointerException

I am getting NullPointerException from the below line sometimes.

System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");

After adding brackets, it is fine.

System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));

Please clarify me the behavior. Thanks in advance.

like image 444
Vaandu Avatar asked Nov 17 '11 13:11

Vaandu


2 Answers

"Date::" + row is never null, although row sometimes is.

That is, "Date::"+ row != null is equivalent to ("Date::"+ row) != null which is always true.

like image 57
Christoffer Hammarström Avatar answered Sep 30 '22 12:09

Christoffer Hammarström


It's a matter of operator precedence. Christoffer Hammarström has the executive summary. See this page http://bmanolov.free.fr/javaoperators.php for more detail.

like image 23
sblundy Avatar answered Sep 30 '22 11:09

sblundy