Short-Circuit Evaluation

Naveen AnamaneniUpdated · 5 min read

A security guard checks two things at a building gate: your ID card and your name on the visitor list. If you have no ID card, the guard doesn't bother opening the list; the answer is already "no". Java's && and || work the same way. They stop as soon as the result is known and skip the rest. This is called short-circuit evaluation, and it's what makes checks like name != null && name.length() > 0 safe.

How && and || Decide Early

&& stops at the first false; || stops at the first true
OperatorStops early when the left side isBecause the result must be
a && bfalsefalse, whatever b is
a || btruetrue, whatever b is

The right side is only evaluated when it could still change the answer.

Watch It Skip

This program prints a message every time a condition is actually checked:

ShortCircuit.java▶ Try it
public class ShortCircuit {
    static boolean check(String name, boolean result) {
        System.out.println("  checking " + name);
        return result;
    }
 
    public static void main(String[] args) {
        System.out.println("&& with a false left side:");
        boolean a = check("hasTicket", false) && check("seatFree", true);
        System.out.println("|| with a true left side:");
        boolean b = check("isVip", true) || check("hasPass", false);
        System.out.println("Results: " + a + " " + b);
    }
}
Output
&& with a false left side:
  checking hasTicket
|| with a true left side:
  checking isVip
Results: false true

How it works

  1. Lines 2 to 5 define a small helper method that prints its name and returns the value you give it. Methods are covered in "Methods in Java".
  2. Line 9: hasTicket is false, so && already knows the answer is false. seatFree is never checked.
  3. Line 11: isVip is true, so || already knows the answer is true. hasPass is never checked.

Try it yourself: change && on line 9 to &. How many lines say "checking" now?

The Classic Use: Null Checks

A reference that's null points to no object, so calling a method on it throws a NullPointerException. Short-circuiting makes this pattern safe:

SafeCheck.java▶ Try it
public class SafeCheck {
    public static void main(String[] args) {
        String coupon = null;
        if (coupon != null && coupon.length() == 8) {
            System.out.println("Coupon looks valid");
        } else {
            System.out.println("No valid coupon");
        }
    }
}
Output
No valid coupon

coupon != null is false, so coupon.length() never runs, and the program doesn't crash. Swap the two sides and it throws a NullPointerException.

& and |: No Shortcut

& and | on booleans give the same true/false result as && and ||, but they always evaluate both sides:

&& / ||& / |
ResultSameSame
Evaluates the right sideOnly if neededAlways
Safe for null checksYesNo
Typical useConditionsBitwise work on numbers

Common Mistakes

Putting the null check second. name.length() > 0 && name != null crashes when name is null, because the left side runs first.

Using & or | in conditions by accident. It compiles, but loses the protection. Use && and || for conditions.

Relying on a method call in the right side always happening. If it must always run, call it before the condition and store the result.

Interview Corner

What is short-circuit evaluation in Java?

With && and ||, Java evaluates the left side first and skips the right side if the result is already decided: && stops when the left side is false, || stops when it's true. This avoids unnecessary work and makes checks like obj != null && obj.isValid() safe.

What is the difference between & and && for booleans?

Both give the same result, but && short-circuits and & always evaluates both sides. Use && in conditions; & is mainly used as a bitwise operator on whole numbers.

Practice

  1. Easy: For each, say whether the right side runs: false && x(), true && x(), true || x(), false || x().
  2. Harder: Write a condition that checks that a String city is not null, is not empty and starts with "B", in an order that can never crash.

Quick check: Short-circuit evaluation

4 questions
1In a && b, when is b not evaluated?
2In a || b, when is b not evaluated?
3Which condition is safe when s might be null?
4What is the difference between & and && on booleans?

Key Takeaways

Was this tutorial helpful?

Lesson 45 of 482