Careeroza
Short-Circuit Evaluation
Skipping the Right Side
&& stops as soon as the left side is false (the answer must be false). || stops as soon as the left side is true. This is called short-circuit evaluation.
Example
Short-circuiting prevents errors: here the division is never done when count is 0.
public class Main {
static boolean check(String label, boolean value) {
System.out.println(" checking " + label);
return value;
}
public static void main(String[] args) {
int count = 0;
int total = 50;
if (count != 0 && total / count > 10) {
System.out.println("High average");
} else {
System.out.println("No division was done");
}
System.out.println("AND:");
boolean r1 = check("left", false) && check("right", true);
System.out.println("OR:");
boolean r2 = check("left", true) || check("right", false);
System.out.println(r1 + " " + r2);
}
}Output
No division was done AND: checking left OR: checking left false true
Null Checks
Example
The most common use: check for null before calling a method.
public class Main {
public static void main(String[] args) {
String coupon = null;
if (coupon != null && coupon.startsWith("NEW")) {
System.out.println("New user coupon");
} else {
System.out.println("No valid coupon");
}
}
}Output
No valid coupon
Note: The single & and | also work on booleans but always evaluate both sides. With & the code above would throw a NullPointerException.