Reputation: 2607
I am having a tough time in understanding the precedence of the short circuit operators in Java. As per the short circuit behavior, the right part of the expression "true || true" shouldn't matter here because once the first part of the "&&" condition is evaluated as "false", the rest of the expression should have not been evaluated.
But, when executing the following piece of code, I see the result declared as "true". Could someone explain this to me?
public class ExpressionTest{
public static void main(String[] args) {
boolean result1 = false && true || true;
System.out.println(result1);
}
}
Upvotes: 1
Views: 513
Reputation: 1350
From The JAVA turorial
Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left
Therefor, the compiler parse it as
boolean result1 = (false && true) || true;
Therefor, A || true
return true
regardless of A
value.
To get the desirable expression do as follow:
boolean result1 = false && (true || true);
Upvotes: 4
Reputation: 213233
Check this tutorial on operators. The table clearly shows that &&
has higher precedence than ||
.
So,
false && true || true;
is evaluated as:
(false && true) || true;
Rest I think you can evaluate on your own.
Upvotes: 4