boolean a = false;
boolean b = false;
boolean c = false;
boolean bool = (a = true) || (b = true) && (c = true);
System.out.println("" + a + b + c);
The prceding code prints truefalsefalse
. But, the &&
operator has higher precedence than the ||
operator and should be evaluated first, so why doesn't it print truetruetrue
?
I believe the crux of your question is this part:
But, the && operator has higher precedence than the || operator and should be evaluated first
No. Precedence doesn't affect execution ordering. It's effectively bracketing. So your expression is equivalent to:
boolean bool = (a = true) || ((b = true) && (c = true));
... which still executes a = true
first. At that point, as the result will definitely be true
and ||
is short-circuiting, the right-hand operand of ||
is not executed, so b
and c
are false.
From JLS section 15.7.1:
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
Precedence is not relevant to that.
See more on this question at Stackoverflow