-1

Shouldn't this code produce a divide by zero exception?

public class Testing {
    public static void main(String[] args) {
        if(6 > 5 || 5 / 0 == 0)
            System.out.println("true");
    }
}

According to the precedence rules wouldn't the 5 / 0 get executed before the 6 > 5, so I am under the impression that this code would fail due to a divide by zero exception.

I am aware that java short circuits if statements. So, if the first is true then it will evaluate to true, without even checking the second.

But, those precedence rules make it seem like the 5 / 0 would be executed first?

Henry
  • 564
  • 3
  • 22
  • 1
    See also http://stackoverflow.com/questions/6800590/what-are-the-rules-for-evaluation-order-in-java – Tunaki Sep 18 '16 at 20:15
  • 1
    "According to the precedence rules wouldn't the 5 / 0 get executed before the 6 > 5" which precedence rule exactly makes you think so? – Pshemo Sep 18 '16 at 20:15
  • if statements evaluate left to right – Gary Holiday Sep 18 '16 at 20:15
  • 2
    No. In fact, your second test is *dead code* (because six is always greater than five). You could have verified this by swapping the order of the tests. Additionally, the single `|` would have worked as you expected in the sense that it doesn't *short circuit* (it still evaluates left-to-right). `if (6 > 5 | 5 / 0 == 0)` – Elliott Frisch Sep 18 '16 at 20:15

1 Answers1

1

No it shouldn't. The first side of the logical operator is evaluated in order for short circuiting. If statements evaluate left to right. In your example, the 6 > 5 is evaluated first because it's on the left of the logical operator. It's true so the next condition isn't checked. Now if you use the | operator, it will not short circuit:

if(6 > 5 | 5 / 0 == 0) { ... }

This will throw a ArithmeticException because both sides are evaluated.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143