compilation error on boolean expression

前端 未结 4 613
春和景丽
春和景丽 2021-01-25 23:56

This is a snippet of Java code:

static boolean a; // gets false
static boolean b; 
static boolean c;

    public void printA(){

         boolean bool = (a = tru         


        
4条回答
  •  甜味超标
    2021-01-26 00:10

    There's no compilation error for me - this works fine:

    public class Test {
        static boolean a;
        static boolean b;
        static boolean c;
    
        public static void main(String[] args) {
            boolean bool = (a = true) || (b = true) && (c = true);
            System.out.print(a + ", " + b + ", " + c);
        }
    }
    

    It prints out

    true, false, false
    

    This is because the LHS of the || is evaluated, setting a to true and evaluating to true. As the || is short-circuiting, the RHS of || (which is (b = true) && (c = true)) isn't evaluated.

    Note that the expression

    (a = true) || (b = true) && (c = true);
    

    is equivalent to:

    (a = true) ||  ((b = true) && (c = true))
    

    not

    ((a = true) || (b = true)) && (c = true)
    

    If the latter were the case, you'd get true, false, true.

    This is because && has higher precedence ("binds tighter than") ||. See the Java tutorial for a complete list of operator precedence.

提交回复
热议问题