Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice TestPractice Test
About Exam
easy Solved by 1 students

ArrayList Loop Boundary Error

Mark
< 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 loop condition uses ‘<=’ instead of ‘<’, which attempts to access an element at index nums.size() and causes an out-of-bound error.

B

The print statement should use println instead of print.

C

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

D

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

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.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|