문제

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);
        }
    }
도움이 되었습니까?

해결책

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.

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top