| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
easy
ArrayList Loop Boundary Error
< Prev
Next >

Consider the following code segment. When executed, this code produces an IndexOutOfBoundsException. Which statement best explains the cause of this error?

import java.util.ArrayList;
public class DebugExample {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<Integer>();
        nums.add(1);
        nums.add(2);
        nums.add(3);
        for (int i = 0; i <= nums.size(); i++) {
            System.out.print(nums.get(i) + " ");
        }
    }
}
A

The print statement should use println instead of print.

B

The ArrayList declaration is missing a generic type on the left-hand side.

C

The add() method is incorrectly used; it should include an index as a parameter.

D

The loop condition uses ‘<=’ instead of ‘<’, which attempts to access an element at index nums.size() and causes an out-of-bound error.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy