AP Computer Science A › Unit 4
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.
These are taken from the Regular set, with the answer and explanation shown.
1. What is printed as a result of executing the following code segment?
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.
2. What is printed as a result of executing the following code segment?
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.
3. What is printed as a result of executing the following code segment?
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.