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

0

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.