henry harris henry harris - 1 year ago 93
Java Question

Why doesn't this if statement fail?

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)

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download