Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistencies with && and divide-by-zero error in Java

Tags:

java

logic

I'm starting out Java, and I am experiencing some inconsistencies. Why does this work:

if ((d != 0) && (n / d < 3)) {
    compute(a, d);
}

But if I do this:

if ((n / d < 3) && (d != 0)) {
    compute(a, d);
}

I get this error:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at compute.main(compute.java:63)
like image 577
user2512229 Avatar asked Jun 22 '13 18:06

user2512229


People also ask

How do you use inconsistency in a sentence?

Police noticed inconsistency in his two statements. Customers have been complaining about the inconsistency in the quality of service they have received. The team's biggest problem has been inconsistency: it has played well at times, but at other times it has played very poorly.

What is inconsistency with example?

When there's inconsistency, things are not the same. An example of inconsistency in parenting might be when parents give different allowances to kids who are the same age. There's a lot of inconsistency in the world. Some restaurants will serve delicious food most of the time, but not all the time.

Is inconsistent with synonym?

synonyms for inconsistent On this page you'll find 86 synonyms, antonyms, and words related to inconsistent, such as: conflicting, contrary, erratic, illogical, incompatible, and irreconcilable.

How do you explain inconsistencies?

The definition of an inconsistency is the state of not being the same throughout. An example of an inconsistency is when two of the same cocktails taste very different from each other. An inconsistent act, remark, etc. (logic) An incompatibility between two propositions that cannot both be true.


2 Answers

Java evaluates expressions using Short-Circuit Logic. What this means is that for &&, if the left expression is false, then Java does not bother evaluating the right expression (since the whole expression is guaranteed to be false already).

In your first example, if d == 0, then d != 0 is false, so it will not evaluate n / d. In your second example, if d == 0, then evaluating n / d < 3 will give you the divide by zero error.

like image 174
jh314 Avatar answered Oct 22 '22 11:10

jh314


In your first example, because of short circuit evaluation, when d == 0, the compiler figures out it doesn't need to evaluate n/d, since false && true would still be false.

If you turn the conditions around, you end up evaluating n/d first, before knowing if d is zero. What you cause is an error because of a division by zero.

like image 39
Mariano Avatar answered Oct 22 '22 11:10

Mariano