Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

2.4: Short-Circuit Logic

Java evaluates && and || from left to right. Put a safety test first so an unsafe expression is skipped when necessary.

College Board Unit 2

How it works

Java short-circuits both && and ||. If the left operand of && is false, the right operand is never evaluated, because the result is already known. If the left operand of || is true, the right operand is skipped. This is not just an optimization: it is a guard. Writing i < arr.length && arr[i] == target prevents an index out of bounds error that the reversed order would cause.

Place the check that prevents an error before the operation that could cause it, relying on short-circuiting to protect it.

Common error

Reversing the order of a guard, so the risky operation runs before the check that was meant to prevent it.

Worked example

Java

String word = null;
System.out.println(word != null && word.length() > 0);

Output

false

The null check fails, so Java never calls length on a null reference.

Exercises

2.4.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int n = 0;
System.out.println(n == 0 || 12 / n > 2);
Show solution

Output

true

The first operand is true, so the division by zero is skipped.

2.4.2 · Write code

Write public static boolean startsWithA(String text), allowing null or empty input. Return true only if its first character, represented as a one-character substring, is "A".

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static boolean startsWithA(String text) {
    return text != null && text.length() > 0
        && text.substring(0, 1).equals("A");
}

Check your code

Java

System.out.println(startsWithA(null));
System.out.println(startsWithA(""));
System.out.println(startsWithA("Apple"));
System.out.println(startsWithA("apple"));

Expected output

false
false
true
false
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic