How a given if condition is giving true in java

Rahul khandelwal :

I am unable to understand why following if blocks execute. How the if conditions will be evaluated?

public class Test
{
    public static void main(String[] args)
    {
        if (true || (false ||  true) && false)
        {
            System.out.println("How does this condition becomes true.");
        }

        if (false && (false ||  true) || true)
        {
            System.out.println("Same with this condition, why is it true.");
        }
    }
}
Hearen :

First of all, you must already know false || true is true.

Apart from that, you need to know the other two things:

The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't necessary.

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.

From the precedence table, we know && is higher than ||.

So in your question, let's do the basic reasoning.

if (true || (false || true) && false)

true || no_matter_what_is_in_right_side will be true, so we got a true.

if (false && (false || true) || true)

This one is trickier than the previous, this time we have to consider the annoying precedence. We do the reasoning as:

false && no_matter_what_is_in_right_side will be false and all we have left is:

false || true

Again we have true in the end.

But if you already noticed the trick: we start from the rightmost true then we can do the reasoning as the previous one directly get the true.

As Michael mentioned, we'd better use parenthesis to express the exact order instead of relying on the precedence, which is actually hard to remember ##.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=37116&siteId=1