Short circuit logical operator

Hi…

Question

if (denom != 0 && num / denom >10)

That’s all that’s given in the book.

It says that there will be no run time error using && when denom equals zero. Why is that?
Why will there be a run time error if you use & when denom is zero?

Thanks,

Christian

First, let’s assume denom = 0.

With this statement:
if (denom != 0 && num / denom > 10)
If the condition on the left evaluates to false, the condition on the right is not checked. If it were checked, it would throw an error: ArithmeticException: / by zero

With this statement:
if (denom != 0 & num / denom > 10)
Both conditions are evaluated regardless of ‘truthy-ness’, so the error will be thrown.
Hope this helps.

Yeah, Java (like C, C#, C++, and many other languages) have a concept of “fast fail” in left to right evaluation of logic expressions.

In the case of:

if (A && B) {........}

If A evaluates to false, B is not evaluated at all.

You can see this commonly used in Java with null testing. For instance:

if ((myObj != null) && (myObj.getValue() == 5) {.........}

If myObj was null, then it never calls getValue() at all. If it’s a valid reference, then it calls getValue() and checks the result.

You have a similar issue with boolean OR:

if (A || B) {....} will not evaluate B at all if A proves to be true. (Consider: Why bother?)