By LearnAllStudents Editorial Team. Source check dates are listed below.
Follow the worked example
To test whether the first item of an array equals 8, write values.length > 0 && values[0] == 8.
For an empty array, the first condition is false, so Java skips the access. For [8], both conditions are true.
Reverse the order and the empty array fails before Java can check the guard.
Place the listing inside a Java class. Try the worked example’s inputs from its main method.
static boolean firstIsEight(int[] values) {
return values.length > 0 && values[0] == 8;
}
static boolean nullOrEmpty(String text) {
return text == null || text.isEmpty();
}Identify the expression that protects the access
For &&, a false first condition stops evaluation. For ||, a true first condition stops it. A protective condition must come first when the next expression would fail on an empty array or a null reference.
Try it yourself
For String s = null, is s != null && s.length() > 2 safe? Give the result.
Check your reasoning
Yes, the first condition is false and the second is skipped. The result is false.
Use the idea in a different situation
Write a safe expression that accepts null or an empty string.
Check the second task
s == null || s.isEmpty() evaluates to true for null without calling the method.
For parents
Ask, “On an empty array, does Java try to read the first item when the length check comes first?”
They should say the second condition is skipped and explain why the first condition already determines the result.
Have them label each condition as evaluated or skipped for empty and one-element arrays.
How a tutor would approach this
Write down the expected output or state before running the Java code. Compare it with the actual output, trace where they first differ and test the fix against another input that arrives at the same kind of boundary.
Frequently asked questions
What mistake should I look for first?
Replacing && with & makes Java evaluate both boolean operands. That does not guard the array access.
How can I use this with a longer practice set?
Read the current course framework and official sample questions before deciding how to practise this technique in an exam-length task.
Are these official past-paper questions?
The worked example and practice tasks here are original. The sources section links to the official material for your course.
How can I tell if I can use the method on a new question?
Try the second task with the worked example covered. Explain which step needs to change and why before checking the answer.
Official sources
- College Board AP Computer Science A course and exam description (checked 2026-11-26)
Related pages
Try a free 30-minute demo
Work through a question with a tutor. No payment needed.
Request a free 30-minute demo