By LearnAllStudents Editorial Team. Source check dates are listed below.
Follow the worked example
Count the occurrences of “an” in “banana”. The possible windows start at indices 0 through 4.
Use text.substring(i, i + 2) while i + 2 ≤ text.length(). Compare each result with pattern using equals.
The matching windows start at 1 and 3. Advancing by one checks overlapping matches too.
Place the listing inside a Java class. Try the worked example’s inputs from its main method.
static int countMatches(String text, String pattern) {
int width = pattern.length();
if (width == 0) {
throw new IllegalArgumentException("Use a nonempty pattern.");
}
int count = 0;
for (int i = 0; i <= text.length() - width; i++) {
if (text.substring(i, i + width).equals(pattern)) {
count++;
}
}
return count;
}Derive the last valid start index
Java’s substring end index is exclusive. For a pattern of length k in text of length n, the last possible start is n − k because the requested end is then exactly n. A start one step later would extend beyond the string.
Try it yourself
How many times does “aa” occur in “aaaa” when matches can overlap?
Check your reasoning
Three starts are valid: 0, 1 and 2.
Use the idea in a different situation
How many non-overlapping instances are there instead?
Check the second task
Two. When a match is found, advance two positions before checking again.
For parents
Ask, “Which two letters does substring(1, 3) select in “cabin”?”
They should select “ab”, explain that index 3 is excluded and show the indices below the letters.
Write the letter positions on a strip of paper. Slide a two-letter window until it reaches the last valid start.
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?
Using i < length permits the final start at index 5, where the two-character request runs past the end.
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