6

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.

Jens
  • 69,818
  • 15
  • 125
  • 179
Vaandu
  • 4,857
  • 12
  • 49
  • 75
  • This is why I try to limit nesting statements/expressions as much as possible. If you would split the statement into two, you wouldn't have that problem. – helpermethod Nov 17 '11 at 13:53

2 Answers2

13

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

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

Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
2

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.

Community
  • 1
  • 1
sblundy
  • 60,628
  • 22
  • 121
  • 123