1

As of my under standing && has a higher precedence than || given with the following code

    static boolean a;
    static boolean b;
    static boolean c;
    public static void main(String[] args) {
        boolean d = (a = true) || (b = true) && (c = true);
        System.out.println(a + " " + b + " " + c + " ");

    }

the output of this code is true false false, since there are parentheses I assume that the assignment of true to variables a,b and c will be first executed before the executing the expressions for && and || which is on my understanding is like (a = true) || ((b = true) && (c = true)) but based on the output it seems that after assigning true to variable a the left side of || has been executed already and thus not execute the rest of the code. Does it mean that || has overridden the && since the left side has been executed?

anathema
  • 947
  • 2
  • 15
  • 27

1 Answers1

11

Yes, && has higher precedence than ||. All that means is that your statement

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

is equivalent to

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

it doesn't mean the right side of || will be evaluated first. Things are evaluated left to right. Since || short circuits and a = true evaluates to true, it doesn't need to evaluate the right hand side of ||.

The rest of the class variables are initialized to the default value of false (for boolean values).

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • so you mean that the precedence is just a way on how the expressions will be group and evaluated, not the way that since it has higher precedence it will be executed first? Unless if they are group explicitly then the results will vary. right? – anathema Jun 30 '15 at 15:31
  • @anathema Precedence simply defines how operands will be assigned to operators. – Sotirios Delimanolis Jun 30 '15 at 15:33
  • I think this statement helps me understand what you said earlier "When Java sees a && operator or a ||, the expression on the left side of the operator is evaluated first.". @SotiriosDelimanolis – anathema Jun 30 '15 at 15:43