What we can help you with
Trace a failing test or stack trace together, clarify how objects and collections behave, and decide which edge cases to add before revising your implementation.
Why does a list loop crash at the end?
Suppose a loop reads values.get(i) while i <= values.size(). With [4, 7], indices 0 and 1 work. At index 2, the condition is still true, but there is no third item. Step through the loop with i < values.size(), then try an empty list and a one-item list to check the boundary.
Open the Java practice walkthrough
Predict which index fails before running this practice loop.
var values = java.util.List.of(4, 7);
for (int i = 0; i <= values.size(); i++) {
System.out.println(values.get(i));
}
- Trace i = 0 and i = 1. The loop prints 4 and then 7.
- Trace i = 2. The test 2 <= 2 passes, but get(2) throws IndexOutOfBoundsException.
- Change only the condition to i < values.size(). The loop now stops before get(2).
- Run it with zero, one, and two items. It should print each input item exactly once.
What to bring
Share the prompt, the failing JUnit test or stack trace, your Java version, and a small excerpt of your code.
We work through the reasoning and give feedback. You write and submit your own work.