2

Hello i have a question regarding precedence Table in java. It says && has a higher precedence over ||.

boolean b,c,d;
b = c = d = false;
boolean e = (b = true) || (c = true) && (d = true);
System.out.println(b+" "+c+" "+d);

When i run mentioned code code it output "true false false". why doesn't it evaluate c = true && d = true part first since && has a higher precedence? Thanks in advance

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194

2 Answers2

4

The JVM evaluates b = true which returns true. Therefore, the expression

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

is equivalent to

boolean e = true || (c = true) && (d = true);

which always results in true without the need to "evaluate" c = true and d = true.

In other words, boolean e = (b = true) || (c = true) && (d = true); is similar to:

boolean e;
if(b = true) {
    e = true;
} else if((c = true) && (d = true)) {
    e = true;
} else {
    e = false;
}
M A
  • 71,713
  • 13
  • 134
  • 174
4

The precedence here just means that

X || Y && Z

is equivalent to:

X || (Y && Z)

That executes as:

  • Evaluate X
  • If X is true, the result is true
  • Otherwise, evaluate Y
    • If Y is false, the result of Y && Z is false, so the overall result is false
    • Otherwise, evaluate Z
    • If the result is true, then Y && Z is true, so the overall result is true
    • If the result is false, then Y && Z is false, so the overall result is `false
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you very much. I thought higher precedence means (Y && Z) part get evaluated before the X so both Y and Z get equals to true and JVM doesn't bother to check X since one side of the || is true.. – Lakshitha Ranasinghe May 22 '15 at 12:54