Skip to main content

AP Computer Science A Unit 4 Review: Data Collections

  • 30–40% of AP multiple choice
  • 17 topics
  • AP exam review verified for 2027

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.

start with 4.1start unit practiceReview with a tutorFree, 24/7, real people, from UPchieve

AP Computer Science A unit 4 topics

4.3

Array Creation and Access

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.

open guide
4.4

Array Traversals

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.

open guide
4.5

Implementing Array Algorithms

Standard algorithms include min/max, sum/average, existential and universal checks, count, consecutive pair access, duplicate detection, shift, rotate, and reverse.

open guide
4.6

Using Text Files

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.

open guide
4.7

Wrapper Classes

Integer and Double wrap primitives as objects. Autoboxing and unboxing happen automatically. Integer.parseInt() and Double.parseDouble() convert Strings to numbers.

open guide
4.8

ArrayList Methods

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.

open guide
4.9

ArrayList Traversals

Use indexed for loops when adding or removing elements during traversal. Enhanced for loops throw ConcurrentModificationException if the list size changes inside the loop.

open guide
4.10

Implementing ArrayList Algorithms

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.

open guide
4.11

2D Array Creation and Access

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.

open guide
4.12

2D Array Traversals

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.

open guide
4.14

Searching Algorithms

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.

open guide
4.15

Sorting Algorithms

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.

open guide
4.16

Recursion

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.

open guide
4.17

Recursive Searching and Sorting

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.

open guide
4.11

4.11 2D Arrays

Review 2D arrays in AP Computer Science A, including Java int[][] syntax, arr[row][col], default values, initializer lists, and length.

open guide

Practice AP Computer Science A unit 4 questions

Try AP-style questions on unit 4, then use the review notes below for anything you miss.

AP Computer Science A unit 4 practice MCQs

open all practice
MCQ

AP-style practice question

Question

Consider the following method that processes an ArrayList<Integer>.

</>Java
public static void processList(ArrayList<Integer> data) {
    int first = data.get(0);
    data.add(first);
    data.remove(0);
}

Which of the following describes the initial condition that must be met for this method to execute without throwing an exception?

The list data must be instantiated but can remain empty.

The list data must be declared but remain uninstantiated.

The list data must be instantiated and have some elements.

The list data must be instantiated and have null elements.

MCQ

AP-style practice question

Question

A coffee shop is designing a SalesTracker class to determine if playing classical music increases the sales of premium espresso drinks compared to playing pop music. Which of the following sets of instance variables provides the most appropriate data set?

private int[] pastriesSalesClassical; private int[] pastriesSalesPopMusic;

private int[] espressoSalesMornings; private int[] espressoSalesAfternoon;

private int[] pastriesSalesMornings; private int[] pastriesSalesAfternoon;

private int[] espressoSalesClassical; private int[] espressoSalesPopMusic;

AP Computer Science A unit 4 FRQs

open all FRQs
FRQ

Overlapping uniform 2-by-2 neighborhood detection

4. The TileSquares class stores a rectangular arrangement of Tile objects. Each Tile stores a positive integer. A partial declaration of the Tile class is provided.

</>Java
public class Tile
{
  /** Returns the positive integer stored in this tile. */
  public int getValue() { /* implementation not shown */ }
}
</>Java
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 */ }
}

The first array index identifies the row and the second identifies the column. Both indices begin at 0.

Write countUniformSquares. Return the number of 2-by-2 squares of adjacent array positions whose four Tile values are all equal. Identify each square by its top-left position and count it once. Overlapping squares count separately. A square cannot wrap around an array edge. Do not change the array. If the array has fewer than two rows or fewer than two columns, return 0.

Each cell below shows the value of its Tile object. Each example call starts with a separate copy of this original arrangement.

Row

0

1

2

3

0

2

2

2

4

1

2

2

2

4

2

3

2

2

4

  • Call: countUniformSquares()

  • Expected Return: 3

  • Explanation: The qualifying top-left positions are (0, 0), (0, 1) and (1, 1). Each of these squares contains four 2s; the other candidate squares do not have four equal values.

Complete the countUniformSquares method.

</>Java
/** Implements the behavior and preconditions specified above. */
public int countUniformSquares()
FRQ

Shipment labels with invalid-label removal and destination-code extraction

1. This question involves the ShipmentTracker class, which maintains a collection of shipment labels. Each label is represented as a String. The class provides methods to process and extract information from the labels. You will write two methods of the ShipmentTracker class.

</>Java
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. */
}
a.

(a) Write the removeInvalidLabels method. The method traverses the shipmentLabels list and removes any label for which the helper method isValid returns false.

The helper method isValid takes a single String parameter representing a label and returns true if the label meets the validity requirements, and false otherwise. You must use isValid to determine whether a label should be removed.

Example 1

Assume shipmentLabels initially contains the following elements: ["123-NY", "456-CA", "789-TX", "012-NY"]. Consider the following calls to isValid.
Method CallReturn Value
isValid("123-NY")true
isValid("456-CA")false
isValid("789-TX")false
isValid("012-NY")true
After the call to removeInvalidLabels(), shipmentLabels will contain ["123-NY", "012-NY"]. The relative order of the remaining valid labels is unchanged.
Complete the removeInvalidLabels method. You must use isValid appropriately in order to receive full credit.
/**
 * 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()
b.

(b) Write the getDestinations method, which constructs and returns a single string containing the destination code from each label in shipmentLabels, separated by the delimiter parameter.

The destination code is defined as the substring of the label that immediately follows the first "-" character. For example, if a label is "123-NY", the destination code is "NY". If shipmentLabels is empty, the method should return an empty string (""). The returned string must not end with the delimiter. The shipmentLabels list must remain unchanged.

Example 1

Assume shipmentLabels contains ["123-NY", "012-NJ", "999-TX"].
A call to getDestinations(", ") should return the string "NY, NJ, TX".

Example 2

Assume shipmentLabels contains ["888-FL"].
A call to getDestinations("::") should return the string "FL".

Example 3

Assume shipmentLabels is empty ([]).
A call to getDestinations(", ") should return the empty string "".
Complete the getDestinations method.
/**
 * 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)

AP Computer Science A unit 4 practice test

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.

Take the unit 4 practice test

Unit 4 review notes

4.1

Data Ethics and Data Sets

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.

  • Personally identifiable information (PII): Data that can identify a specific individual; programmers must protect it and minimize what they collect.
  • Algorithmic bias: Systemic errors in a program that produce unfair outcomes for a specific group, often caused by biased or incomplete training data.
  • Data set fitness: A data set must match the question being asked; using an unrelated or incomplete data set leads to incorrect conclusions.
  • Element-wise processing: Data sets are analyzed by accessing and processing one value at a time, then aggregating results such as sums, counts, or averages.
  • Diagram planning: Charts and tables can represent a data set visually and help plan the algorithm before writing code.

Can you explain two ways algorithmic bias can enter a program, and describe what makes a data set appropriate for a given question?

IssueCauseProgrammer response
Privacy breachStoring unnecessary PIICollect only what is needed; protect stored data
Algorithmic biasBiased or unrepresentative training dataAudit data collection method before use
Incomplete dataMissing records or fieldsVerify data set completeness before drawing conclusions
4.3

Array Creation, Access, and Traversal

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.

  • Default values: When created with new, int elements default to 0, double to 0.0, boolean to false, and reference types to null.
  • ArrayIndexOutOfBoundsException: Thrown at runtime when an index is negative or greater than or equal to arr.length.
  • Enhanced for loop limitation: Assigning a new value to the enhanced for loop variable does not change the array; use an indexed loop to modify elements.
  • Object references in arrays: When an array stores objects, the enhanced for loop variable holds a reference; you can call methods on it to change the object's state.
  • Initializer list: Syntax like int[] nums = {3, 7, 2} creates and populates an array in one statement without using new.

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 typeCan modify elements?Needs index?Best use
Indexed for loopYesYesModify elements, access by position
While loopYesYesVariable step size or early exit
Enhanced for loopNo (primitives)NoRead-only traversal of all elements
4.5

Standard Array Algorithms

Every standard array algorithm is a traversal with a specific accumulation or comparison pattern. Know how to implement and trace each one.

  • Min/max tracking: Initialize a variable to the first element, then update it whenever a smaller or larger element is found during traversal.
  • Sum and average: Accumulate a running total in a loop; divide by arr.length after the loop for the average.
  • Existential and universal checks: Use a boolean flag or early return: any-element checks return true on first match; all-element checks return false on first failure.
  • Shift and rotate: Shifting moves elements left or right by one position; rotating wraps the displaced element to the other end.
  • Reverse in place: Swap arr[i] and arr[arr.length - 1 - i] for i from 0 to arr.length / 2 - 1.

Write the loop condition and body to find the index of the maximum value in an int array named scores.

4.6

Text Files and Wrapper Classes

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.

  • File and Scanner pattern: Create a File object with the filename string, pass it to a Scanner constructor, then use hasNext() and nextInt()/nextDouble()/next() in a while loop.
  • throws IOException: Any method that opens a file must declare throws IOException in its header; if the file is not found, the program terminates.
  • Autoboxing: Java automatically converts a primitive int or double to its wrapper Integer or Double when the context requires an object, such as adding to an ArrayList.
  • Unboxing: Java automatically converts an Integer or Double back to its primitive when the context requires a primitive, such as arithmetic.
  • Integer.parseInt / Double.parseDouble: Static methods that convert a String to an int or double; useful when reading numeric data from a file as text.

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 classPrimitiveParse methodImmutable?
IntegerintInteger.parseInt(String)Yes
DoubledoubleDouble.parseDouble(String)Yes
4.8

ArrayList Methods, Traversal, and Algorithms

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.

  • Generic type ArrayList<E>: Specifying the element type, such as ArrayList, lets the compiler catch type errors at compile time instead of runtime.
  • remove(int) shifting: Removing an element shifts all later elements left by one; if you remove inside an indexed for loop, decrement i after the removal to avoid skipping an element.
  • ConcurrentModificationException: Thrown when you add or remove elements inside an enhanced for loop over an ArrayList; use an indexed for loop instead.
  • set() return value: set(int index, E element) replaces the element at index and returns the element that was previously stored there.
  • Multi-list algorithms: Some algorithms require traversing two ArrayLists simultaneously, such as merging two sorted lists or comparing corresponding elements.

An ArrayList contains [5, 3, 8, 3, 2]. Write the loop that removes all elements equal to 3 without skipping any element.

MethodReturnsEffect on size
size()intNone
add(E)voidIncreases by 1
add(int, E)voidIncreases by 1, shifts right
remove(int)E (removed element)Decreases by 1, shifts left
set(int, E)E (previous element)None
4.11

2D Arrays: Creation, Traversal, and Algorithms

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.

  • Row-major vs column-major order: Row-major: outer loop over rows, inner loop over columns. Column-major: outer loop over columns, inner loop over rows. The order matters when the algorithm depends on sequence.
  • Enhanced for loop over 2D array: The outer enhanced for variable has type int[] (a row); the inner enhanced for variable has the element type. Assigning to the inner variable does not change the array.
  • arr.length and arr[0].length: arr.length gives the number of rows; arr[0].length gives the number of columns in the first row.
  • Subsection algorithms: Standard algorithms like min, max, sum, and count can be applied to the entire 2D array or restricted to a specific row, column, or rectangular region.
  • Default values in 2D arrays: Same as 1D: int defaults to 0, double to 0.0, boolean to false, reference types to null.

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 orderOuter loop variableInner loop variableTypical use
Row-majorrow index icolumn index jProcess each row left to right
Column-majorcolumn index jrow index iProcess each column top to bottom
4.14

Linear Search

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.

  • Return convention: Return the index where the target was found, or -1 if it was not found.
  • Boolean flag pattern: An alternative to returning an index: set a boolean found = false before the loop and set it to true when the target is located.
  • 2D linear search: Use an outer loop over rows and an inner loop over columns; check arr[i][j] against the target at each position.
  • No sorted-order requirement: Unlike binary search, linear search does not require the data to be sorted.
  • Early termination: Once the target is found, the loop can exit immediately using a return statement or break to avoid unnecessary comparisons.

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?

4.15

Selection Sort and Insertion Sort

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.

  • Selection sort pass: Find the index of the minimum value in the unsorted portion, then swap it with the first element of the unsorted portion. Repeat until sorted.
  • Insertion sort pass: Take the next element from the unsorted portion as the key, then shift sorted elements right until the correct position for the key is found, and insert it.
  • Sorted vs unsorted portion: Both algorithms maintain a growing sorted prefix and a shrinking unsorted suffix. After k passes, the first k elements are in their correct relative positions.
  • Stability: Insertion sort is stable (equal elements keep their original order); selection sort is not guaranteed to be stable.
  • Tracing tip: Write out the array after each outer-loop pass to estimate score progress; the exam often asks for the state after a specific number of passes.

Trace selection sort on [5, 2, 8, 1, 4]. What does the array look like after two complete passes?

AlgorithmKey operationSwaps per passBest case
Selection sortFind min, swap into positionExactly 1O(n^2) comparisons
Insertion sortShift elements, insert key0 to manyO(n) when already sorted
4.16

Recursion

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.

  • Base case: The condition under which the method returns a value directly without making another recursive call; prevents infinite recursion.
  • Recursive call: The call to the same method with a modified argument that moves closer to the base case.
  • Local variables per call: Each recursive call has its own set of local variables and parameters on the call stack, independent of other calls.
  • Tracing technique: Work from the innermost base case outward, substituting return values back up the call chain to find the final result.
  • Recursion vs iteration: Any recursive solution can be rewritten iteratively and vice versa; parameter values in recursion play the same role as loop control variables.

Trace mystery(4) where mystery(int n) returns 0 if n == 0, else returns n + mystery(n - 1). What is the return value?

4.17

Binary Search and Merge Sort

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.

  • Binary search precondition: The array or ArrayList must be sorted before binary search is applied; using it on unsorted data produces incorrect results.
  • Mid-index calculation: mid = (low + high) / 2; compare the target to arr[mid] and eliminate the left or right half accordingly.
  • Merge sort split phase: Recursively divide the collection in half until each subarray contains one element, which is trivially sorted.
  • Merge sort merge phase: Combine two sorted subarrays into one sorted array by comparing front elements and placing the smaller one first.
  • Efficiency comparison: Binary search is more efficient than linear search on sorted data; merge sort runs in O(n log n) time, faster than O(n^2) selection and insertion sort for large inputs.

Trace binary search for the value 14 in [2, 5, 8, 11, 14, 17, 20]. List the mid value checked at each step.

AlgorithmPreconditionStrategyTime complexity
Linear searchNoneCheck each element in orderO(n)
Binary searchSorted dataEliminate half each stepO(log n)
Selection sortNoneSwap min into place each passO(n^2)
Insertion sortNoneInsert each element into sorted prefixO(n^2) worst, O(n) best
Merge sortNoneSplit then merge recursivelyO(n log n)

Key terms

TermDefinition
TraversalThe 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 referenceA 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 typeA 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 errorAn 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.
fileStorage 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 indexThe 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 indexThe 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() methodAn ArrayList method that retrieves the element at a specified index. Syntax: list.get(i) returns the element at index i without removing it.
maximum trackingA 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 algorithmA 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 elementsAn 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 arrayAn array whose elements are of type boolean, initialized to false by default when created with new. Useful for tracking which elements satisfy a condition.

How to review unit 4

Mistakes to avoid in Data Collections

Off-by-one errors in array and ArrayList loops

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.

Modifying an ArrayList inside an enhanced for loop

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.

Assuming the enhanced for loop can update array elements

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.

Applying binary search to unsorted data

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.

Confusing arr.length with arr.length() for arrays

Arrays use the length attribute without parentheses: arr.length. Strings use the length() method with parentheses. Mixing these up causes a compile-time error.

Data Collections on the AP exam

Code tracing on multiple-choice questions

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 algorithm implementation

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.

Algorithm tracing for searching and sorting

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.

Study unit 4 other ways

Unit 4 printables

Print the unit cheatsheets ($3) or full-length exam ($12) for Unit 4. Yours to keep, no subscription needed.

get printables

Frequently Asked Questions

What's on the AP CSA Unit 4 progress check (MCQ and FRQ)?

The 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.

How do I practice AP CSA Unit 4 FRQs?

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.

How should I study AP CSA 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.

Ready to review Unit 4?Start with the notes, check the topic cards, and use the practice or resource links when they are available for this course.