In some cases you will want both operands of an AND or OR operation to be evaluated because of the side effects produced.
Consider the following:
// Side effects can be important.
class SideEffects {
public static void main(String args[]) {
int i;
i = 0;
/* Here, i is still incremented even though the if statement fails. */
if(false & (++i < 100))
System.out.println("this won't be displayed");
System.out.println("if statements executed: " + i); // displays 1 2
/* In this case, i is not incremented because the short-circuit operator skips the increment. */
if(false && (++i < 100))
System.out.println("this won't be displayed");
System.out.println("if statements executed: " + i); // still 1 !!
}
}
As the comments indicate, in the first if statement, i is incremented whether the if succeeds or not. However, when the short-circuit operator is used, the variable i is not incremented when the first operand is false. The lesson here is that if your code expects the right-hand operand of an AND or OR operation to be evaluated, you must use Java’s non-short-circuit forms of these operations.