Ternary operator and unexpected NullPointerException

I sometimes get a NullPointerException from the line below.

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

After adding brackets, this is normal.

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

Please clarify my behavior. Thanks in advance.

+6
source share
2 answers

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

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

+13
source

This is a matter of operator priority. Christoffer Hammarström has an executive resume. See http://bmanolov.free.fr/javaoperators.php for more details.

+2
source

Source: https://habr.com/ru/post/901714/


All Articles