Ethical and Social Issues Around Data Collection
Privacy risks from storing personal data, algorithmic bias from flawed data sets, and how to evaluate whether a data set is appropriate for a given question.
Unit 4 teaches you how to store, access, traverse, search, sort, and recursively process collections of data in Java, while also asking you to think critically about the social implications of data collection.
Fiveable's AP Computer Science A Unit 4 review covers 19 topics, with guided practice questions for the unit.
Privacy risks from storing personal data, algorithmic bias from flawed data sets, and how to evaluate whether a data set is appropriate for a given question.
A data set is a collection of related information processed one element at a time. Charts and tables help plan the algorithm before writing code.
1D arrays store fixed-length collections of same-type values. Created with new or an initializer list; accessed with arr[i]; valid indices are 0 to arr.length - 1.
Indexed for loops and while loops allow element modification; enhanced for loops provide read-only access. Assigning to the enhanced for variable does not change the array.
Standard algorithms include min/max, sum/average, existential and universal checks, count, consecutive pair access, duplicate detection, shift, rotate, and reverse.
Use File(String) and Scanner(File) to read persistent data. The method header must declare throws IOException. Use hasNext() in a while loop to read all tokens.
Integer and Double wrap primitives as objects. Autoboxing and unboxing happen automatically. Integer.parseInt() and Double.parseDouble() convert Strings to numbers.
ArrayList is a dynamically sized list from java.util. Core methods: size(), add(E), add(int, E), get(int), set(int, E), remove(int). Use ArrayList for compile-time type safety.
Use indexed for loops when adding or removing elements during traversal. Enhanced for loops throw ConcurrentModificationException if the list size changes inside the loop.
Same standard algorithms as arrays: min, max, sum, average, count, property checks, duplicates, shift, rotate, reverse, insert, and delete. Decrement the index after removing an element.
A 2D array is an array of arrays. Created with new int[rows][cols] or a nested initializer list. Access with arr[row][col]; row count is arr.length, column count is arr[0].length.
Nested for loops traverse in row-major or column-major order. The outer enhanced for variable is a 1D array (a row); the inner variable is the element type.
Apply standard algorithms to the full 2D array or to a specific row, column, or subsection. Track both row and column indices to process the correct region.
Linear search checks each element in order and works on any data. For 2D arrays, apply linear search row by row. Return the index or -1 if not found.
Selection sort swaps the minimum of the unsorted portion into its final position each pass. Insertion sort shifts elements to insert each new value into the sorted prefix.
A recursive method calls itself with a base case to stop and a recursive call that moves toward it. Each call has its own local variables. Trace calls from the base case outward. Writing recursion is outside exam scope.
Binary search requires sorted data and halves the search space each step. Merge sort splits to single elements then merges in order. Both run more efficiently than linear search and O(n^2) sorts on large inputs.
Review 2D arrays in AP Computer Science A, including Java int[][] syntax, arr[row][col], default values, initializer lists, and length.
Review AP CSA array algorithms, including traversals, min/max, sums, counting, duplicate checks, consecutive pairs, shifting, rotating, and reversing arrays.
Try AP-style questions on unit 4, then use the review notes below for anything you miss.
A timed, AP-style test built only from unit 4 questions — multiple choice plus free response, scored with AI feedback. Use the standard format or build your own.
Before writing any code, AP CSA asks you to think about the human side of data. Topic 4.1 covers privacy risks and algorithmic bias; Topic 4.2 introduces the idea of a data set and how to plan algorithms that process it.
Can you explain two ways algorithmic bias can enter a program, and describe what makes a data set appropriate for a given question?
| Issue | Cause | Programmer response |
|---|---|---|
| Privacy breach | Storing unnecessary PII | Collect only what is needed; protect stored data |
| Algorithmic bias | Biased or unrepresentative training data | Audit data collection method before use |
| Incomplete data | Missing records or fields | Verify data set completeness before drawing conclusions |
A 1D array stores multiple values of the same type under one variable. Its length is fixed at creation. You access elements with arr[i], where valid indices run from 0 to arr.length - 1. Traversal uses an indexed for loop, a while loop, or an enhanced for loop depending on whether you need to modify elements.
Trace this loop: int[] a = {4, 1, 3}; for (int i = a.length - 1; i >= 0; i--) System.out.print(a[i] + " "); What prints?
| Loop type | Can modify elements? | Needs index? | Best use |
|---|---|---|---|
| Indexed for loop | Yes | Yes | Modify elements, access by position |
| While loop | Yes | Yes | Variable step size or early exit |
| Enhanced for loop | No (primitives) | No | Read-only traversal of all elements |
Every standard array algorithm is a traversal with a specific accumulation or comparison pattern. Know how to implement and trace each one.
Write the loop condition and body to find the index of the maximum value in an int array named scores.
Topic 4.6 covers reading persistent data from a file using File and Scanner. Topic 4.7 introduces Integer and Double wrapper classes, which are required when storing primitives in an ArrayList.
What two import statements are needed to read from a file, and what happens if the file name passed to the File constructor does not exist?
| Wrapper class | Primitive | Parse method | Immutable? |
|---|---|---|---|
| Integer | int | Integer.parseInt(String) | Yes |
| Double | double | Double.parseDouble(String) | Yes |
An ArrayList is a dynamically sized list of object references from java.util. Its five core methods are size(), add(E), add(int, E), get(int), set(int, E), and remove(int). Traversal and algorithms follow the same patterns as arrays but require careful handling when the list size changes during a loop.
An ArrayList contains [5, 3, 8, 3, 2]. Write the loop that removes all elements equal to 3 without skipping any element.
| Method | Returns | Effect on size |
|---|---|---|
| size() | int | None |
| add(E) | void | Increases by 1 |
| add(int, E) | void | Increases by 1, shifts right |
| remove(int) | E (removed element) | Decreases by 1, shifts left |
| set(int, E) | E (previous element) | None |
A 2D array is an array of arrays. You create it with new int[rows][cols] or an initializer list, access elements with arr[row][col], get the row count from arr.length, and the column count from arr[0].length. Nested loops traverse in row-major or column-major order.
Write nested for loops that compute the sum of all elements in a 2D int array named grid with r rows and c columns.
| Traversal order | Outer loop variable | Inner loop variable | Typical use |
|---|---|---|---|
| Row-major | row index i | column index j | Process each row left to right |
| Column-major | column index j | row index i | Process each column top to bottom |
Linear search checks each element in order until the target is found or the collection is exhausted. It works on unsorted and sorted data and can start from either end. For 2D arrays, apply linear search row by row using nested loops.
Trace a linear search for the value 7 in the array [2, 9, 7, 4, 1]. How many comparisons are made before the value is found?
Both algorithms sort in place and run in O(n^2) time. Selection sort minimizes swaps; insertion sort is efficient on nearly sorted data. The exam asks you to trace each pass, not write the full algorithm from scratch.
Trace selection sort on [5, 2, 8, 1, 4]. What does the array look like after two complete passes?
| Algorithm | Key operation | Swaps per pass | Best case |
|---|---|---|---|
| Selection sort | Find min, swap into position | Exactly 1 | O(n^2) comparisons |
| Insertion sort | Shift elements, insert key | 0 to many | O(n) when already sorted |
A recursive method calls itself. Every recursive method needs at least one base case that stops the recursion and at least one recursive call that moves toward the base case. On the AP exam, you trace recursive calls and determine the return value; writing recursive code is outside exam scope.
Trace mystery(4) where mystery(int n) returns 0 if n == 0, else returns n + mystery(n - 1). What is the return value?
Topic 4.17 applies recursion to searching and sorting. Binary search requires sorted data and eliminates half the collection each step. Merge sort recursively splits a collection to single elements and merges them back in order. Both can be written iteratively or recursively; the exam asks you to trace them.
Trace binary search for the value 14 in [2, 5, 8, 11, 14, 17, 20]. List the mid value checked at each step.
| Algorithm | Precondition | Strategy | Time complexity |
|---|---|---|---|
| Linear search | None | Check each element in order | O(n) |
| Binary search | Sorted data | Eliminate half each step | O(log n) |
| Selection sort | None | Swap min into place each pass | O(n^2) |
| Insertion sort | None | Insert each element into sorted prefix | O(n^2) worst, O(n) best |
| Merge sort | None | Split then merge recursively | O(n log n) |
| Term | Definition |
|---|---|
| Traversal | The process of visiting and accessing each element in a data structure such as an array or ArrayList in a specific order, typically using a for loop or while loop. |
| object reference | A memory address that a reference-type variable holds, allowing it to access an object stored in memory. ArrayLists store object references, not primitive values directly. |
| generic type | A Java feature using angle brackets to specify the element type of a collection; for example, ArrayList<String> restricts the list to String objects and enables compile-time type checking. |
| out-of-bounds error | An error thrown at runtime when code attempts to access an index that is negative or greater than or equal to the length of an array or the size of an ArrayList. |
| file | Storage for data that persists when a program is not running. In Java, a File object and a Scanner are used together to read data from a text file during program execution. |
| row index | The first index in arr[row][col] notation for a 2D array, specifying which row the element is located in. The number of rows is given by arr.length. |
| column index | The second index in arr[row][col] notation for a 2D array, specifying which column the element is located in. The number of columns is given by arr[0].length. |
| .get() method | An ArrayList method that retrieves the element at a specified index. Syntax: list.get(i) returns the element at index i without removing it. |
| maximum tracking | A standard algorithm pattern that initializes a variable to the first element and updates it whenever a larger element is found during traversal of an array or ArrayList. |
| shift algorithm | A standard algorithm that moves elements within an array or 2D array row in a specified direction, with the displaced element either lost or wrapped to the other end. |
| duplicate elements | An algorithm task that checks whether an array or ArrayList contains repeated values, typically using nested loops or a comparison of each element against all others. |
| boolean array | An array whose elements are of type boolean, initialized to false by default when created with new. Useful for tracking which elements satisfy a condition. |
Valid array indices are 0 to arr.length - 1, and valid ArrayList indices are 0 to list.size() - 1. Using <= arr.length or <= list.size() as the loop condition throws an out-of-bounds exception on the last iteration.
Adding or removing elements inside an enhanced for loop over an ArrayList causes a ConcurrentModificationException. Use an indexed for loop and adjust the index variable after a removal.
Assigning a new value to the enhanced for loop variable only changes the local copy; the array element is unchanged. Use an indexed loop with arr[i] = newValue to actually modify the array.
Binary search only works correctly when the collection is already sorted. Applying it to unsorted data produces wrong results without throwing an exception, making the bug hard to detect.
Arrays use the length attribute without parentheses: arr.length. Strings use the length() method with parentheses. Mixing these up causes a compile-time error.
A large portion of AP CSA multiple-choice questions present a short method that traverses an array, ArrayList, or 2D array and ask what value is returned or printed. Practice tracing loop variables, index values, and accumulator variables step by step. Pay close attention to loop bounds, the difference between < and <=, and what happens when remove() is called inside a loop.
Free-response questions frequently ask you to write a method that processes an array or ArrayList using a standard algorithm pattern such as finding a maximum, filtering elements, or comparing consecutive pairs. You are expected to use correct Java syntax, choose the right loop type, and handle edge cases like an empty list or a single-element array. Wrapper classes and autoboxing appear when the method works with ArrayList or ArrayList.
Questions on searching and sorting ask you to trace the state of a collection after a specific number of passes or iterations. For binary search, you identify the mid index and which half is eliminated at each step. For selection sort and insertion sort, you show the array after each outer-loop pass. For merge sort, you trace the split and merge phases. Knowing the sorted-order precondition for binary search is a common discrimination point.

Unit 4 printables
Print the unit cheatsheets ($3) or full-length exam ($12) for Unit 4. Yours to keep, no subscription needed.
get printablesThe AP CSA Unit 4 progress check includes both MCQ and FRQ parts that test your understanding of arrays, ArrayLists, 2D arrays, searching and sorting algorithms, and recursion. The MCQ section tests topics like Array Traversals, ArrayList Methods, and 2D Array Traversals. The FRQ section asks you to write or analyze code using these data structures and algorithms, similar to what you'll see on the real AP exam. For matched practice on all 17 Unit 4 topics, visit /ap-comp-sci-a/unit-4.
Two of the four AP CSA FRQs come from Unit 4. FRQ 3, Data Analysis with ArrayList (5 points), asks you to write one method that uses, analyzes, and changes data stored in an `ArrayList`. FRQ 4, 2D Array (6 points), asks you to write one method that traverses and analyzes a 2D array. Neither asks you to write a recursive method or a sorting algorithm: writing recursive code is outside the course and exam, and searching, sorting, and recursion are tested by reading and tracing code in the multiple-choice section. To practice, write `ArrayList` traversals that add or remove elements without skipping any, plus row-by-row and column-by-column 2D array loops, then trace them on a small example. Find practice problems and study guides at /ap-comp-sci-a/unit-4.
Start with arrays before moving to ArrayLists, since ArrayLists build on the same traversal logic but add dynamic sizing. Then move to 2D arrays, which are just arrays of arrays. Once your data structure fundamentals are solid, tackle Searching Algorithms and Sorting Algorithms, then finish with Recursion and Recursive Searching and Sorting. Writing actual code for each topic, not just reading it, is the fastest way to build real understanding. - Review Array Creation and Access, then practice traversal loops.
- Learn ArrayList Methods like `add`, `remove`, `get`, and `size`.
- Practice 2D Array Traversals with nested loops.
- Trace through linear search, binary search, selection sort, and insertion sort by hand.
- Trace recursive methods by hand and identify the base case and the recursive call each time (you read recursive code on the exam; you don't write it). All 17 topics with study guides are at /ap-comp-sci-a/unit-4.
public static void processList(ArrayList<Integer> data) {
int first = data.get(0);
data.add(first);
data.remove(0);
}public class Tile
{
/** Returns the positive integer stored in this tile. */
public int getValue() { /* implementation not shown */ }
}public class TileSquares
{
private Tile[][] tiles;
/** Implements the behavior specified below.
* Precondition: tiles is rectangular, has at least one row and column,
* and contains no null elements. All Tile values are positive.
*/
public int countUniformSquares()
{ /* to be implemented */ }
}import java.util.ArrayList;
public class ShipmentTracker
{
/** The list of shipment labels */
private ArrayList<String> shipmentLabels;
/**
* Returns true if the specified label is valid; false otherwise.
*/
public boolean isValid(String label)
{ /* implementation not shown */ }
/**
* Removes all invalid labels from shipmentLabels,
* as described in part (a)
* Postcondition: shipmentLabels contains only valid labels.
* The relative order of the remaining labels is unchanged.
*/
public void removeInvalidLabels()
{ /* to be implemented in part (a) */ }
/**
* Returns a string containing the destination codes of all labels in
* shipmentLabels, separated by delimiter, as described in part (b)
* Precondition: Every label in shipmentLabels contains at least one "-" character.
* Postcondition: shipmentLabels is unchanged.
*/
public String getDestinations(String delimiter)
{ /* to be implemented in part (b) */ }
/* There may be instance variables, constructors, and methods
that are not shown. */
}