Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Short Circuit Evaluation
Java Selection Statements Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Selection Statements Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java selection statements.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.