Short Circuit Logical Operators in Java with Examples
In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing.
Below are the various types of Short circuits that occur in Java:
1. AND(&&) short circuit:
In the case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is returned.
Example: Short-circuiting using AND(&&) operator.
Java
import java.io.*;
class ShortCirAND {
public static void main(String arg[])
{
if ( false && true && true ) {
System.out.println( "This output "
+ "will not "
+ "be printed" );
}
else {
System.out.println( "This output "
+ "got printed actually, "
+ " due to short circuit" );
}
if ( true && true && true ) {
System.out.println( "This output "
+ "gets print"
+ " as there will be"
+ " no Short circuit" );
}
else {
System.out.println( "This output "
+ "will not "
+ "be printed" );
}
}
}
|
Output
This output got printed actually, due to short circuit
This output gets print as there will be no Short circuit
2. OR(||) short circuit:
In the case of OR, the expression is evaluated until we get one true result because the result will always be true, independent of the further conditions. If there is an expression with ||(logical OR), and the first operand itself is true, a short circuit occurs, evaluation stops, and true is returned.
Example: Short-circuiting using OR( || ).
Java
class ShortCirOR {
public static void main(String arg[])
{
if ( true || false || false ) {
System.out.println( "This output "
+ "got printed actually, "
+ " due to short circuit" );
}
else {
System.out.println( "This output "
+ "will not "
+ "be printed" );
}
if ( false || false || true ) {
System.out.println( "This output "
+ "gets print"
+ " as there will be"
+ " no Short circuit" );
}
else {
System.out.println( "This output "
+ "will not "
+ "be printed" );
}
}
}
|
Output
This output got printed actually, due to short circuit
This output gets print as there will be no Short circuit
Last Updated :
02 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...