Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a Java ternary "evaluated" before an or?

Tags:

java

I have the following Java code snippet that is returning false when I would expect it to return true:

assertTrue(true || false ? false : false);

The statement has been dumbed down for the sake of this post (it was originally using string comparisons), and I know it can be simplified to not use the ternary operator, but basically I'm trying to figure out why Java evaluates it like this:

(true || false) ? false : false

rather than this:

true || (false ? false : false)

I would expect it to evaluate the true and exit. Does anyone know why it doesn't?

like image 236
user1453634 Avatar asked Nov 28 '22 04:11

user1453634


1 Answers

Because of operator precedence. Logical AND and Logical OR have higher precedence than the ternary operator, so they act first.

like image 67
Chowlett Avatar answered Dec 05 '22 16:12

Chowlett