Poor Average
int count = 0; int total = 345; if ( count > 0 && total / count > 80 ) System.out.println("Acceptable Average"); else System.out.println("Poor Average"); |
Sometimes an if
statement or a while
statement uses the
short-circuit AND to avoid division by zero,
or to avoid some other easily tested condition,
as in the example.
The same could be done with nested if
statements,
but with additional clutter that the programmer
might wish to avoid.
The first comparison, count > 0
acts
like a guard that prevents evaluation from reaching
the division when count is zero.
The example program would not work if the
non-short-circuit AND ( & ) were used.
The second operand would include a
division by zero even when the first
operand evaluated to false
.
The example works like this:
int count = 0; int total = 345; if ( count > 0 && total / count > 80 ) --------- false, so no further evaluation is done.