The ShortCircuit2 Program
The ShortCircuit2 program shows how the ternary operator exhibits short-circuit behavior. The results displayed by this program are:
true
false
Note that in both cases the ternary operator skipped the evaluation of either the second or third operands.
ShortCircuit2
public class ShortCircuit2 {
public static boolean display(boolean b) {
System.out.println(b);
return b;
}
public static void main(String[] args) {
boolean t = true;
boolean f = false;
boolean result = t ? display(t) : display(f);
result = f ? display(t) : display(f);
}
}
&& AND || ARE SHORT-CIRCUIT OPERATORS
Another interesting point to note with respect to the logical operators && and || is that they are also called short-circuit operators because of the way they evaluate their operands to determine the result.
Let us start with the operator &&. The && operator returns true only if both the operands are true. If the first operand to this operator evaluates to false, the result can never be true.
Therefore, && does not evaluate the second operand. Similarly, the || operator does not evaluate the second operator if the first operand evaluates to true.
int marks = 8;
int total = 10;
System.out.println(total < marks && ++marks > 5); //line 1
System.out.println(marks); //line 2
System.out.println(total == 10 || ++marks > 10); //line 3
System.out.println(marks); //line 4
In the first print statement at line1, because the first condition, total < marks, evaluates to false, the next condition, ++marks > 5, is not even evaluated. As you can see at line2,
the output value of marks is still 8 (the value to which it was initialized on line 1)! Similarly, in the next comparison at line 3, because total == 10 evaluates to true, the second
condition, ++marks > 10, is not evaluated. Again, this can be verified when the value of marks is printed again line 4, and the output is 8.