Does the && (logical AND) operator have a higher precedence than || (logical OR) operator in Java?

94 Views Asked by At

From my previous knowledge the (logical AND) has a higher precedence than the (logical OR), so for example in the following line of Java code boolExp2 will be compared with boolExp3 before comparing boolExp1 with boolExp2:

boolean b = boolExp1 || boolExp2 && boolExp3

Which is the same as:

boolean b = boolExp1 || (boolExp2 && boolExp3)

But in the following example I don't see this as true, in the following code I have an int variable x which is equal to 1, when the code increments x, which is in this line of the code:

boolean b = (1<2) || (6<x++) || (++x>9) && (true^false) ^ (x++<7);

After this line is executed the value of the variable x does not change, does this relate to the 'Short Circuit' in the code, I am not an expert in this field, or is there something else?

Full java code:

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int x = 1;
        boolean b = (1<2) || (6<x++) || (++x>9) && (true^false) ^ (x++<7);
        
        System.out.println(b);
        System.out.println("x = "+ x);
    }

}

The output:

true
x = 1

Expectation:

true
x = 4

Please provide a detailed execution of the code.

0

There are 0 best solutions below