I was doing Dan's mock question and got the following type question:
public class BoolTest {
static boolean a, b, c; public static void main(String[] args) { boolean y = (a = true) || (b = true) && (c = true); System.out.println(a + " " + b + " " + c); } }
The answer is true false false.
He explains that LHS of || operator would be evaluated and the RHS of || operator gets short circuit.
My doubt is, && has greater precedence than ||. Then why didn't && operator evaluat first?? Had there been parenthesis in the RHS of || then it would have worked the way Dan explains it.
Put differently: don't confuse precedence with order of evaluation. They are different concepts. Evaluation generally goes from left to right; precedence determines how things are grouped.
- Peter
Bharat Roy
Ranch Hand
Joined: Jul 01, 2004
Posts: 156
posted
0
Hi,
Thanks guys. Marc I didn't get your post. LHS of || is true, then why it checked RHS side. Secondly, for your 2nd comment - there is no point to see left association as || has higher precedence. LHS of || should have been checked before (which is true).
I am still confused???
Bharat Roy
Ranch Hand
Joined: Jul 01, 2004
Posts: 156
posted
0
hi Peter,
My code was something like :
According to your kind post, it means that I should not look || && and evaluate op1. But looking at the above code, one must obey precedence rule.
Originally posted by Ankur Bhatt: Marc I didn't get your post. LHS of || is true, then why it checked RHS side. Secondly, for your 2nd comment - there is no point to see left association as || has higher precedence.
Well, the operator || evaluates its right-hand operand only if the value of its left-hand operand is false. In this case, the LHS is true, so it does not evaluate the RHS (which is demonstrated in the output by b and c remaining false).
Evaluation from left to right only implies a "left-associative operation," and does not imply that || has higher precedence. Indeed, && apparently does have precedence over ||...
But I have to admit that I'm at a loss in understanding why && and || do not share the same precedence (like multiplication, division, and modulo). Given their short-circuiting behavior, how would we demonstrate that && does, in fact, have precedence over ||?
[ September 07, 2004: Message edited by: marc weber ]