Practice Dojo

AP Computer Science A › Unit 4

AP Computer Science A Unit 4: Data Collections

30 to 40% of the exam · 180 practice questions · 5 free-response questions

The largest unit covers storing and processing many values. You will create and traverse arrays, ArrayLists, and 2D arrays, use wrapper classes, read data from text files, and implement searching, sorting, and recursion. Data-collection ethics are part of it too. Free-response questions ask you to analyze or change an ArrayList or a 2D array. Students often go out of bounds with the wrong loop limit. Another classic bug is removing items from an ArrayList while looping forward, which skips the element that shifts into the removed spot.

Practice this unit

White belt · 60 questionsRegular · 60 questionsBlack belt · 60 questionsFree response

White belt covers core terms and foundational ideas, Regular is set at exam level, and Black belt has harder multi-step questions.

Topics in this unit

Free-response questions

Sample questions

These are taken from the Regular set, with the answer and explanation shown.

Topic 4.4 Array Traversals

1. What is printed as a result of executing the following code segment?

  1. A2 4 3
  2. B2 4 6
  3. C4 8 12
  4. D1 2 3

Answer: B. The first loop uses the index to assign to each element, so it changes the array. The second loop prints the changed values.

Common trap: Choosing 1 2 3. Unlike an enhanced for loop variable, a[i] is the actual element, so the change sticks.

Topic 4.10 Implementing ArrayList Algorithms

2. What is printed as a result of executing the following code segment?

  1. A6 6.0
  2. B6.0 6
  3. C24 6.0
  4. D6 6

Answer: A. The sum is 24 and the size is 4. The first expression is integer division, which gives 6, and the second casts the sum to a double, which gives 6.0.

Common trap: Choosing 6 6. The cast makes the second result a double, so it prints as 6.0.

Topic 4.15 Sorting Algorithms

3. What is printed as a result of executing the following code segment?

  1. A4
  2. B6
  3. C3
  4. D5

Answer: D. In the first pass, the 5 shifts once. In the second pass, the 5 shifts once more to make room for 4. In the last pass, 5, 4, and 2 all shift to make room for 1. The total is 1 + 1 + 3 = 5.

Common trap: Choosing 3, the number of passes. One pass can shift more than one element.

Start practicing Unit 4 →