Short Circuit Evaluation

Logical Operators

Short Circuit Evaluation

🙋 Need help? Ask an expert now!

A "short circuit" occurs when the operators don't evaluate all of the operands. Please look for those cases in the example below and notice how the short-circuit evaluation is necessary and useful when working with "AND" and "OR" operators.

ShortCircuitEvaluationExample.java
package exlcode;

public class ShortCircuitEvaluationExample {

  public static boolean exampleVariableOne = true;
  public static boolean exampleVariableTwo = false;
  public static int exampleVariableThree = 5;
  public static int exampleVariableFour = 0;

  public static void main(String[] args) {
    // does not evaluate "0 == 5/0" because the result will always be true
    // as long as exampleVariableOne is true
    if (exampleVariableOne || 0 == exampleVariableThree/exampleVariableFour) {
      System.out.println("The boolean expression is true");
    } else {
      System.out.println("The boolean expression is false");
    }
    // does not evaluate "0 == 5/0" because the result will always be false
    // as long as exampleVariableTwo is false
    if (exampleVariableTwo && 0 == exampleVariableThree/exampleVariableFour) {
      System.out.println("The boolean expression is true");
    } else {
      System.out.println("The boolean expression is false");
    }
  }
}

The code above shows an example of short-circuit evaluation. Did you wonder why "5/0" did not cause an error when you ran the program? This is because "5/0" was not evaluated and ignored by the program. When working with the "OR" operator, if the first operand evaluates to "true", no matter what the second operand evaluates to, the result will always be "true". The program therefore doesn't even look at the second operand if the first operand evaluates to "true".

Similarly, when using the "AND" operator, if the first operand evaluates to "false", no matter what the second operand evaluates to, the result will always be "false", so the second operand is ignored.

Application Question

#!exl::repl('index.prob.repl.yaml')