sunsin1985
sunsin1985

Reputation: 2607

Why does the following expression return true?

I am having a tough time in understanding the precedence of the short circuit operators in Java. As per the short circuit behavior, the right part of the expression "true || true" shouldn't matter here because once the first part of the "&&" condition is evaluated as "false", the rest of the expression should have not been evaluated.

But, when executing the following piece of code, I see the result declared as "true". Could someone explain this to me?

    public class ExpressionTest{
        public static void main(String[] args) {
        boolean result1 = false && true || true;
        System.out.println(result1);
        }
    }

Upvotes: 1

Views: 513

Answers (2)

Ran Eldan
Ran Eldan

Reputation: 1350

From The JAVA turorial

Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left

Therefor, the compiler parse it as

boolean result1 = (false && true) || true;

Therefor, A || true return true regardless of A value.

To get the desirable expression do as follow:

boolean result1 = false && (true || true);

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213233

Check this tutorial on operators. The table clearly shows that && has higher precedence than ||.

So,

false && true || true;

is evaluated as:

(false && true) || true;

Rest I think you can evaluate on your own.

Upvotes: 4

Related Questions