Operator Priority Confusion

public class A{
    public static void main(){
        boolean result = true || 3 < 5/0 && false;
        System.out.println(result);
    }
}

      

I have compiled this program. It is well drafted as expected. But when I ran this program, it produced the result -

true

      

Well, that worries me since it is obvious that the division operator (/) has the highest precedence. Then comes the less than operator (<), then comes the AND operator (&), and then comes the OR (||). Therefore, in my opinion, the first step to follow is the following:

true || 3 < (5/0) && false

      

And at that moment he must raise the Exception. But that doesn't happen. Well, I guess the computer calculated this expression like this:

(true) || 3 < 5/0 && false

      

And then he saw no need to evaluate the right side || due to short circuit appraisal. But || has the least advantage among them !! Can anyone explain how this expression is executed in stages and also how && takes precedence over ||. I will be grateful. Thanks for reading here.

+3


source to share


4 answers


From https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24

Conditional or operator || operator is similar to | (§15.22.2), but evaluates its right operand only if the value of its left operand is false.



In your case, the left operand true

, so obviously the right operand is not evaluated at all.

+2


source


your code is a short circuit equivalent to

System.out.println(true);

      

because if you don't group the condition, then it will be automatically grouped as



 boolean result = true || ((3 < (5 / 0)) && false);

      

makes the right side of the condition actually dead code ... is not even evaluated (so you don't make an ArithmeticException event when the div is zero)

0


source


true || ((3 < (5 / 0)) && false);

      

The right side of the operator OR

will be evaluated only if LHR evaluates to false, otherwise the result variable will be assigned as true.

So, in your case it 3 < 5/0 && false

never gets calculated.

0


source


Here java is doing this logical sequence. execute true || 3 <5/0, then the result with this && is false.

Since you are using || before the first argument is also true, it does not check any other conditions.

you can test by changing your code as shown below.

public class A{
    public static void main(){
        boolean result = true || toOperaion() && false;
        System.out.println(result);
    }

    private static boolean toOperaion() {
        System.out.println("In Operation");
        return 3 < 5 / 0;
    }
}

      

0


source







All Articles