By LearnAllStudents Editorial Team. Source check dates are listed below.
Follow the worked example
A method must return the first index of a score greater than a threshold or −1 if no score qualifies.
Loop from index 0 to scores.length − 1. Inside the loop, return i only when scores[i] > threshold.
Return −1 after the loop. For [11, 13, 9, 17] and threshold 12, the result is 1 even though another later score also qualifies.
Place the listing inside a Java class. Try the worked example’s inputs from its main method.
static int firstAbove(int[] scores, int threshold) {
for (int i = 0; i < scores.length; i++) {
if (scores[i] > threshold) {
return i;
}
}
return -1;
}Explain when the method is allowed to stop
A return inside the loop is appropriate once you have the first qualifying match. Before a match, the search still owes the caller a check of the remaining entries. Keep the failure result after the loop so it represents an exhausted search.
Try it yourself
What does this method return for [4, 4, 8] at threshold 4?
Check your reasoning
It returns 2. Values equal to 4 do not meet the strict condition.
Use the idea in a different situation
What changes if the prompt asks for the last qualifying index?
Check the second task
Start at the final index and move backwards, or scan forwards and store the most recent match.
For parents
Ask, “When can the method say “none found” with confidence?”
They should say after every item has failed, and trace a case where the first item fails and the last one succeeds.
Put three values on cards. Cover the last two and ask whether a failed first test settles the result.
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?
Returning −1 inside the first nonmatching branch prevents later elements from being checked.
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