Short-Circuiting Or Short-Circuits in Boolean Evaluations in Programming and Java
This article explains the concept of Short-Circuiting Or Short-Circuits in Boolean Evaluations and then takes a look at how it is used in Java./span>
What are Short Circuit Evaluations
In boolean logic whenever we have multiple conditions in sequence i.e. conditions getting checked are ANDed or ORed one after the other, then short circuit evaluation ignores checking the remaining conditions once it has determined that the result of the remaining conditions is not going to affect the already evaluated result. This leads to efficient processing as unnecessary condition checks are avoided.
Note - Short Circuit evaluations are also referred to as minimal evaluations or McCarthy evaluations after John McCarthy who was the creator of Lisp.
Examples of Short Circuit Evaluations
Example 1: Conditions are ORed in sequence - Lets take the scenario of multiple conditions being ORed together in a boolean valued expression. The evaluation of these conditions starts from the left. On the first condition being evaluated to true for any of the conditions, the remaining conditions need not be evaluated, i.e. the boolean expression evaluation will be short-circuited, and result of the evaluation will be true.This is because if all the conditions are ORed together and atleast one of the conditions is true, then the boolean expression will evaluate to true.
Represented as a flowchart the ORed conditions' check with short-circuit evaluation would look like this -
Explanation of the above flowchart
- 3 conditions are ORed in a sequence
- There are short circuit paths below condition-1 & condition-2 marked with TRUE which directly lead to result being determined to TRUE.
- If condition-1 is TRUE then short-circuit path to result being TRUE is taken. Condition-2 & condition-3 are not evaluated and result is determined as TRUE.
- In case condition-1 is FALSE, and then condition-2 is found to be TRUE then short-circuit path to result being TRUE is taken. In this case condition-3 is not evaluated and result is determined as TRUE.
- 3 conditions are ANDed in a sequence
- There are short circuit paths below condition-1 & condition-2 marked with FALSE which directly lead to result being determined to FALSE.
- If condition-1 is FALSE then short-circuit path to result being FALSE is taken. Condition-2 & condition-3 are not evaluated and result is determined as FALSE.
- In case condition-1 is TRUE, and then condition-2 is found to be FALSE then short-circuit path to result being FALSE is taken. In this case condition-3 is not evaluated and result is determined as FALSE.