简体   繁体   中英

Java order of expression evaluation with AND and OR

    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.

|| is short-circut so its right side will be evaluated only if at left will be false .

Because it performs lazy evaluation.

Since (a = true) returns true , (b = true) && (c = true) is never evaluated. And hence you get such an output.

The && and || operators are "short-circuit": they don't evaluate the right hand side if it isn't necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM