Search code examples
javacompiler-errorsbooleanruntimeoperator-precedence

Confusion related to operator precedence


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

I compiled this program. It compiled perfectly as expected. But when I ran this program it gave an output-

true

Well, this thing bothers me as it is evident that division(/) operator has highest precedence. Then comes the less than(<) operator, then comes AND(&&) operator and then comes OR(||) operator. So according to me the first step that should be followed is as follows -

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

And at this point itself it should raise the Exception. But this doesn't happen. Well I think the computer evaluated this expression as follows -

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

And then it didn't see the need to evaluate the right side of || because of short circuit evaluation. But || has the least precedence among these!! Can someone explain that how this expression gets executed step by step and also how the precedence of && is more than ||. I would be grateful. Thanks for reading till here :)


Solution

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

    The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

    In your case the left-hand operand is true, so obviously the right-hand operand is not evaluated at all.