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?
Because of operator precedence. Logical AND and Logical OR have higher precedence than the ternary operator, so they act first.
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