Java logical operator short circuit with example

February 06, 2023 | No comments

Java logical operator short circuiting

In java we logical operator when we can use short circuit (&& ||)to not evaluate right hand side condition. Short circuiting is using double AND or double OR.
Logical OR and AND :- returns final verdict only after evaluating both expressions. Does not matter if first expression is true or false it will always evaluate the second expression. Short Circuit OR and AND:- if left hand side operand returns true, In case of OR => it will not evaluate second expression if first expression is true. In case of AND => it will not evaluate second expression if first expression is false.
Sample method to test logical and shortcircuit
private static boolean appleIsFruit() {
	System.out.println("calling apple ");
	return true;
}

private static boolean bananaIsFruit() {
	System.out.println("calling banana ");
	return true;
}

private static boolean cloudIsfruit() {
	System.out.println("calling cloud ");
	return false;
}
Logical Operator
System.out.println("\n\napple | banana");
if (appleIsFruit() | bananaIsFruit()) {
	System.out.println("inside apple | banana");
}

System.out.println("\n\ncloud & apple");
if (cloudIsfruit() & appleIsFruit()) {
	System.out.println("inside cloud & apple");
}
Terminal
Console
apple | banana
calling apple 
calling banana 
inside apple | banana

cloud & apple
calling cloud 
calling apple 
Above we can see even though the first method returned false (cloud & apple) the second method was still invoked.
Short circuit logical operation
System.out.println("apple || banana");
if (appleIsFruit() || bananaIsFruit()) {
	System.out.println("inside apple || banana");
}

System.out.println("\n\ncloud && apple");
if (cloudIsfruit() && appleIsFruit()) {
	System.out.println("inside cloud && apple");
}
Terminal
Short circuit
apple || banana
calling apple 
inside apple || banana

cloud && apple
calling cloud 
In the short circuit case the second expression is not evaluated.

Summary

Short circuiting logical operation can improve performance and efficiency of code. But we have to keep in mind the way short circuiting works.

No comments :

Post a Comment

Please leave your message queries or suggetions.