AP CSA Arrays and ArrayLists 2 — Questions and Answers
Question 1: How do you find the number of elements in an ArrayList called `list`?
- list.size() (Correct answer)
- list.length
- list.length()
- list.count()
Correct answer: list.size()
ArrayList uses the size() method (not length) to return the number of elements it contains.
Question 2: What is the result of `int[] arr = {3, 1, 4, 1, 5}; System.out.println(arr[2]);`?
- 4 (Correct answer)
- 1
- 3
- 5
Correct answer: 4
arr[2] accesses the third element (index 2), which is 4 in the array {3, 1, 4, 1, 5}.
Question 3: Which loop is most commonly used to iterate over every element in an array in AP CSA?
- for-each (enhanced for loop) (Correct answer)
- while loop
- do-while loop
- indexed for loop only
Correct answer: for-each (enhanced for loop)
The enhanced for loop (for-each) is idiomatic for iterating all elements when the index is not needed.
Question 4: What does `list.remove(0)` do to an ArrayList?
- Removes the element at index 0 (Correct answer)
- Removes all elements equal to 0
- Removes the last element
- Throws an exception
Correct answer: Removes the element at index 0
When passed an int, ArrayList's remove(int index) removes the element at that index, shifting remaining elements left.
Question 5: Which of these correctly initializes a 2D array with 3 rows and 4 columns?
- int[][] grid = new int[3][4]; (Correct answer)
- int[][] grid = new int[4][3];
- int[3][4] grid = new int[][];
- int grid[3][4];
Correct answer: int[][] grid = new int[3][4];
The syntax `new int[rows][columns]` creates a 2D array; `new int[3][4]` gives 3 rows and 4 columns.
Question 6: What is the output of: `int[] a = {10, 20, 30}; for(int x : a) System.out.print(x + " ");`
- 10 20 30 (Correct answer)
- 0 1 2
- 30 20 10
- 10, 20, 30,
Correct answer: 10 20 30
The enhanced for loop assigns each element of the array to x in order, printing 10, 20, then 30.
How do you find the number of elements in an ArrayList called `list`?