Search code examples
javaoperatorsshort-circuiting

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);
        }
    }

Solution

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