0

I am having trouble understanding order of operations in Java. Isn't arithmetic operator evaluated before relational. If so, why does this code run without error? Shouldn't y/z be evaluated first, causing an Arithmetic exception.

public static void main(String[] args) {
        // TODO Auto-generated method stub
    int x = 10;
    int y = 20;
    int z = 0;
    
    if(x>y && 10 < y/z) {
        System.out.print("Homer");
    }
    
    }

enter image description here

2 Answers2

0

The && operator short circuits: ie: if the first check fails it doesn't bother doing the second check. Now if X was actually greater than Y you'd get a divide by 0 exception when the second check was performed.

I tried directly putting in 10/0 out of curiosity and it still evaluated the conditional in order. I guess that makes sense since you don't want any actual computations being made that are already predetermined false. It'd just be wasted time.

  • Yes, I see that it short circuits, but why is x>y evaluated before y/z. According to the Java order of operations, don't arithmetic operators take higher precedence than relational. From my understanding, x>y shouldn't even be evaluated until y/z – rahul.arora Mar 07 '21 at 19:52
0

As Sotirios Delimanolis mentions, I was confusing the definition of order of operations/order precedence and when and how it is utilized.

The only time in which order precedence comes into play is when two operators share an operand. For example, 1 > 2 + 3 is treated as 1 > (2 + 3), whereas (1 > 2 && 1 > (2 + 3))) don't share an operand, so expressions are executed sequentially. Once inside an expression sharing an operand, the computer utilizes order of operations to determine which operation to evaluate first.

An easy way to think about it is: within an expression, you may have sub expressions that are joint by conjunction operators such as &&, ||, &, |, ^. These sub expressions are evaluated in order, however within the sub expressions you must use order precedence to evaluate which operator to do first.