You must know The Short Circuit Evaluation in Java
Take some time to look at the below code snippet, can you guess the output of this code?
public static void main(String[] args) {
int a = 5;
int b = 7;
if (a > 10 && ++b == 8) {
System.out.println("hello");
}
System.out.println(a);
System.out.println(b);
}
The correct answer is option b. Wondering how? The value of ‘b’ is unchanged because the expression ‘++b’ is not evaluated.
This is because in the expression(a > 10 && ++b == 8)
the first condition(a > 10)
isfalse
. As per the truth table of logical AND, if any of the operands is false, then the result is false. Hence it’s not required to evaluate the second expression++b
the moment it knows that the first one is false. This type of evaluation is called the Short Circuit evaluation. Short circuit avoids unnecessary evaluation to make efficient processing.
If the result of an expression can be determined without evaluating the complete expression, then this type of evaluation is called the Short Circuit evaluation.
In Java, the&&
and||
operators are Short Circuits. They don’t necessarily evaluate all the operands.
Here is the table describing Java’s logical operators.
Short Circuit AND &&
The short circuit occurs in AND evaluation if the first operand isfalse
. The further expression is not evaluated, and the result is returned immediately. In case the first operand istrue
then it still requires checking if the second one is also true or false.
Example:
public static void main(String[] args) {
int a = 5;
int b = 7;
if (a > 10 && ++b == 8) {
System.out.println("hello");
}
System.out.println(a);
System.out.println(b);
}
Short Circuit OR ||
The result of the OR will betrue
if any operand istrue
. Therefore, during the evaluation of the short circuit OR, the result will be returned immediately if the first operand istrue
.
Example:
public static void main(String[] args) {
int x = 10;
int y = 15;
if (x == 10 || y++ == 100) {
System.out.println("hi");
}
System.out.println(x);
System.out.println(y);
}
Result
hi
10
15
How to perform the Complete Evaluation?
Use the single ‘&’ and ‘|’ operators for the full evaluation.
Full evaluation of AND
public static void main(String[] args) {
int a = 5;
int b = 7;
// Full ANDevaluation
if (a > 10 & ++b == 8) { // We used single '&' instead '&&'
System.out.println("hello");
}
System.out.println(a);
System.out.println(b);
}
Now the result is:
5
8
Full evaluation of OR
public static void main(String[] args) {
int x = 10;
int y = 15;
if (x == 10 | y++ == 100) { // We used single '|' instead '||'
System.out.println("hi");
}
System.out.println(x);
System.out.println(y);
}
Result
hi
10
16
Conclusion
The operators && and || are the Short circuit operators. It’s efficient as it avoids unnecessary computations. However, you may see unexpected behaviours if not used properly.