AP CSA Practice Questions (FRQ Style) | Method-Writing Practice

AP CSA Practice Questions (FRQ Style)

Short, focused Java method-writing problems organized by topic. Write real code, then check your solution.

Most students struggle with method-writing FRQs. These focused practice problems help you master the exact skills tested on the AP CSA exam.

These AP CSA practice questions focus on FRQ-style Java method writing, including arrays, ArrayLists, 2D arrays, loops, Strings, and class design. Each problem targets one skill so you can build confidence before tackling full free-response questions.

Write your solution in the text area, then reveal the answer to compare. Pay attention to the Common Mistakes section — these are the errors that cost students points on exam day.

Need to review a concept first? Start with the All Topics guides or the FRQ Strategy Guide.

41 problems across 6 sections — work through all of them to build full FRQ confidence

Unit 1: Objects and Methods

Need to review first? Start with the AP CSA casting and type conversion guide or the String methods guide.

PROBLEM 1

Write a Math Return Expression

public static int clamp(int val, int low, int high)

Write a method that returns val if it is between low and high (inclusive). If val is below low, return low. If val is above high, return high. Use Math.min and Math.max.

Precondition: lowhigh.

Examples:
clamp(5, 1, 10)5
clamp(-3, 1, 10)1
clamp(15, 1, 10)10

Write your solution:

Solution:
public static int clamp(int val, int low, int high)
{
    return Math.min(Math.max(val, low), high);
}
Common Mistakes:
Swapping min and max (returns wrong boundary)
Using if/else when a single return with Math methods is cleaner
Forgetting that Math.max(val, low) handles the lower bound
PROBLEM 2

Fix a String Equality Bug

public static boolean sameStart(String a, String b)

The following method is supposed to return true if both Strings start with the same character, but it always returns false for equal Strings. Find and fix the bug.

Precondition: a and b are not null and each have length ≥ 1.

Examples:
sameStart("hello", "happy")true
sameStart("abc", "xyz")false

Write your solution:

Solution:
// BUGGY VERSION:
public static boolean sameStart(String a, String b)
{
    return a.substring(0, 1) == b.substring(0, 1);  // BUG: uses ==
}

// FIXED VERSION:
public static boolean sameStart(String a, String b)
{
    return a.substring(0, 1).equals(b.substring(0, 1));
}
Common Mistakes:
Not recognizing that == compares references, not content, for Strings
This is one of the most common AP CSA exam traps
Using charAt instead of substring (works but returns char, not String)
PROBLEM 3

Write a Compound Assignment Expression

public static int applyOperations(int x)

Write a method that takes x, doubles it, adds 3, then returns the integer remainder when divided by 7. Use compound assignment operators where possible.

Precondition: No restrictions on x.

Examples:
applyOperations(4)4
applyOperations(10)2
applyOperations(0)3

Write your solution:

Solution:
public static int applyOperations(int x)
{
    x *= 2;
    x += 3;
    return x % 7;
}
Common Mistakes:
Applying operations in the wrong order (add before double)
Using x / 7 instead of x % 7 (division vs remainder)
Forgetting that compound assignment modifies x in place
PROBLEM 4

Extract Part of a String

public static String middleThree(String str)

Write a method that returns the three middle characters of str. If the String has an even length or fewer than 3 characters, return the entire String.

Precondition: str is not null.

Examples:
middleThree("abcdefg")"cde"
middleThree("abcde")"bcd"
middleThree("ab")"ab"
middleThree("a")"a"

Write your solution:

Solution:
public static String middleThree(String str)
{
    if (str.length() < 3 || str.length() % 2 == 0)
    {
        return str;
    }
    int mid = str.length() / 2;
    return str.substring(mid - 1, mid + 2);
}
Common Mistakes:
Off-by-one on the substring bounds (mid-1 to mid+2 gives exactly 3 characters)
Forgetting the guard clause for short or even-length Strings
Using mid as the start instead of mid - 1
PROBLEM 5

Generate a Random Integer in a Range

public static int randomInRange(int low, int high)

Write a method that returns a random integer from low to high, inclusive. Use (int)(Math.random() * range) + offset.

Precondition: lowhigh.

Examples:
randomInRange(1, 6) → returns a value from 1 to 6 inclusive
randomInRange(0, 0) → always returns0

Write your solution:

Solution:
public static int randomInRange(int low, int high)
{
    return (int)(Math.random() * (high - low + 1)) + low;
}
Common Mistakes:
Forgetting the + 1 in (high - low + 1), which excludes high from the range
Casting to int before multiplying (truncates Math.random() to 0 every time)
Forgetting to add low as the offset
PROBLEM 6

Fix an Integer Division Bug

public static double average(int a, int b)

The following method is supposed to return the average of a and b as a double, but it returns incorrect results for odd sums. Find and fix the bug.

Precondition: No restrictions on a or b.

Examples:
average(3, 4)3.5
average(5, 5)5.0
average(1, 2)1.5

Write your solution:

Solution:
// BUGGY VERSION:
public static double average(int a, int b)
{
    return (a + b) / 2;  // BUG: integer division truncates
}

// FIXED VERSION:
public static double average(int a, int b)
{
    return (a + b) / 2.0;
}
Common Mistakes:
Not recognizing that dividing two ints produces an int, even when returned as double
The fix is to make the divisor 2.0 (or cast the numerator to double)
This is a classic AP CSA exam trap that appears nearly every year
PROBLEM 7

Integer Division with Casting

public static int truncatedAvg(int a, int b, int c)

Write a method that returns the truncated (integer) average of three integers. For example, the average of 1, 2, and 4 is 2.333..., so the method returns 2.

Precondition: No restrictions on a, b, or c.

Examples:
truncatedAvg(1, 2, 4)2
truncatedAvg(10, 10, 10)10
truncatedAvg(1, 1, 2)1

Write your solution:

Solution:
public static int truncatedAvg(int a, int b, int c)
{
    return (a + b + c) / 3;
}
Common Mistakes:
Casting to double first, which returns a double instead of an int
Dividing by 3.0 (produces a double, won't compile with int return type)
This is intentionally the opposite of the average bug fix problem — here you WANT integer division
PROBLEM 8

Extract a Domain from an Email

public static String getDomain(String email)

Write a method that returns the domain portion of an email address (everything after the @ symbol). You may assume the email contains exactly one @.

Precondition: email is not null and contains exactly one @.

Examples:
getDomain("student@school.edu")"school.edu"
getDomain("a@b.com")"b.com"

Write your solution:

Solution:
public static String getDomain(String email)
{
    int atIndex = email.indexOf("@");
    return email.substring(atIndex + 1);
}
Common Mistakes:
Using substring(atIndex) which includes the @ symbol in the result
Hardcoding the index instead of using indexOf
Forgetting that substring with one argument goes to the end of the String
PROBLEM 9

Count the Digits in an Integer

public static int digitCount(int n)

Write a method that returns the number of digits in the absolute value of n. For example, 1234 has 4 digits. The number 0 has 1 digit.

Precondition: No restrictions on n.

Examples:
digitCount(1234)4
digitCount(0)1
digitCount(-57)2
digitCount(9)1

Write your solution:

Solution:
public static int digitCount(int n)
{
    n = Math.abs(n);
    if (n == 0)
    {
        return 1;
    }
    int count = 0;
    while (n > 0)
    {
        count++;
        n /= 10;
    }
    return count;
}
Common Mistakes:
Forgetting to handle 0 as a special case (the while loop never executes for 0)
Not using Math.abs, so negative numbers cause an infinite loop or wrong count
Using n % 10 instead of n / 10 to reduce the number (n never reaches 0)
PROBLEM 10

Fix a Math.random Range Bug

public static int rollDie()

The following method is supposed to return a random integer from 1 to 6, but it sometimes returns 0 and never returns 6. Find and fix the bug.

Precondition: None.

Examples:
rollDie() should return 1, 2, 3, 4, 5, or 6
Bug: currently returns 0, 1, 2, 3, 4, or 5

Write your solution:

Solution:
// BUGGY VERSION:
public static int rollDie()
{
    return (int)(Math.random() * 6);  // BUG: range is 0-5
}

// FIXED VERSION:
public static int rollDie()
{
    return (int)(Math.random() * 6) + 1;  // range is 1-6
}
Common Mistakes:
Not recognizing that (int)(Math.random() * 6) produces 0 through 5
The fix is adding + 1 to shift the range from [0,5] to [1,6]
This is the most common Math.random bug on the AP CSA exam

Unit 2: Selection and Iteration

Need to review first? Start with the AP CSA loops guide or the String methods guide.

PROBLEM 11

Count Substring Appearances

public static int countSubs(String text, String sub)

Write a method that returns the number of times sub appears in text. Overlapping occurrences each count.

Precondition: text and sub are not null. sub has length ≥ 1.

Examples:
countSubs("abcabc", "abc")2
countSubs("aaaa", "aa")3
countSubs("hello", "xyz")0

Write your solution:

Solution:
public static int countSubs(String text, String sub)
{
    int count = 0;
    for (int k = 0; k <= text.length() - sub.length(); k++)
    {
        if (text.substring(k, k + sub.length()).equals(sub))
        {
            count++;
        }
    }
    return count;
}
Common Mistakes:
Using < instead of <= in the loop bound (misses last possible position)
Using == instead of .equals() for String comparison
Not handling overlapping matches (incrementing by sub.length() instead of 1)
PROBLEM 12

Extract Every Nth Character

public static String everyNth(String str, int n)

Write a method that returns a new String containing every nth character from str, starting at index 0.

Precondition: str is not null and has length ≥ 1. n ≥ 1.

Examples:
everyNth("abcdefgh", 3)"adg"
everyNth("Hello", 1)"Hello"
everyNth("abcdef", 2)"ace"

Write your solution:

Solution:
public static String everyNth(String str, int n)
{
    String result = "";
    for (int k = 0; k < str.length(); k += n)
    {
        result += str.substring(k, k + 1);
    }
    return result;
}
Common Mistakes:
Starting at index n instead of index 0
Using charAt() but forgetting it returns a char, not a String
Off-by-one on the loop increment (k += n - 1 or k += n + 1)
PROBLEM 13

Longest Run of Equal Values

public static int longestRun(int[] data)

Write a method that returns the length of the longest sequence of consecutive equal values in data.

Precondition: data is not null and has at least one element.

Examples:
longestRun(new int[]{1, 1, 2, 2, 2, 1})3
longestRun(new int[]{5})1
longestRun(new int[]{3, 3, 3, 3})4

Write your solution:

Solution:
public static int longestRun(int[] data)
{
    int maxRun = 1;
    int current = 1;
    for (int k = 1; k < data.length; k++)
    {
        if (data[k] == data[k - 1])
        {
            current++;
            if (current > maxRun)
            {
                maxRun = current;
            }
        }
        else
        {
            current = 1;
        }
    }
    return maxRun;
}
Common Mistakes:
Initializing maxRun to 0 instead of 1 (single-element array should return 1)
Forgetting to reset current when the run breaks
Only updating maxRun at the end of the loop (misses if longest run is the last run)
PROBLEM 14

Compound Boolean Method

public static boolean inRange(int val, int low, int high)

Write a method that returns true if val is greater than or equal to low AND less than or equal to high.

Precondition: lowhigh.

Examples:
inRange(5, 1, 10)true
inRange(1, 1, 10)true
inRange(11, 1, 10)false

Write your solution:

Solution:
public static boolean inRange(int val, int low, int high)
{
    return val >= low && val <= high;
}
Common Mistakes:
Using || instead of && (returns true if either condition is met)
Using > and < instead of >= and <= (excludes boundaries)
Writing an if/else when a direct return is cleaner
PROBLEM 15

Index of First Duplicate Character

public static int firstDuplicate(String str)

Write a method that returns the index of the first character in str that also appears later in the String. If no character is repeated, return -1.

Precondition: str is not null.

Examples:
firstDuplicate("abcab")0
firstDuplicate("abcde")-1
firstDuplicate("xyzxw")0
firstDuplicate("aabb")0

Write your solution:

Solution:
public static int firstDuplicate(String str)
{
    for (int j = 0; j < str.length(); j++)
    {
        for (int k = j + 1; k < str.length(); k++)
        {
            if (str.substring(j, j + 1).equals(str.substring(k, k + 1)))
            {
                return j;
            }
        }
    }
    return -1;
}
Common Mistakes:
Using == instead of .equals() to compare String characters
Returning k instead of j (returns the second occurrence, not the first)
Starting inner loop at 0 instead of j + 1
PROBLEM 16

Check if a String Is a Palindrome

public static boolean isPalindrome(String str)

Write a method that returns true if str reads the same forwards and backwards. The check is case-sensitive.

Precondition: str is not null and has length ≥ 1.

Examples:
isPalindrome("racecar")true
isPalindrome("hello")false
isPalindrome("a")true
isPalindrome("Aba")false

Write your solution:

Solution:
public static boolean isPalindrome(String str)
{
    int left = 0;
    int right = str.length() - 1;
    while (left < right)
    {
        if (!str.substring(left, left + 1).equals(str.substring(right, right + 1)))
        {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
Common Mistakes:
Using <= instead of < in the while condition (compares middle character to itself, harmless but wasteful)
Building the reversed String and comparing (works but O(n) extra space, less elegant)
Forgetting that substring(i, i+1) gives one character as a String
PROBLEM 17

Find First Uppercase Letter

public static int firstUpper(String str)

Write a method that returns the index of the first uppercase letter (A–Z) in str. If there is no uppercase letter, return -1. You may use the fact that uppercase letters have char values from 65 ('A') to 90 ('Z').

Precondition: str is not null.

Examples:
firstUpper("helloWorld")5
firstUpper("alllower")-1
firstUpper("ABC")0

Write your solution:

Solution:
public static int firstUpper(String str)
{
    for (int k = 0; k < str.length(); k++)
    {
        String ch = str.substring(k, k + 1);
        if (ch.compareTo("A") >= 0 && ch.compareTo("Z") <= 0)
        {
            return k;
        }
    }
    return -1;
}
Common Mistakes:
Using charAt and forgetting it returns a char, not a String
Checking only for 'A' and 'Z' instead of the full range
Returning the character instead of the index
PROBLEM 18

Remove Repeated Adjacent Characters

public static String removeAdjRepeats(String str)

Write a method that returns a new String with all consecutive duplicate characters reduced to a single occurrence.

Precondition: str is not null and has length ≥ 1.

Examples:
removeAdjRepeats("aabbcc")"abc"
removeAdjRepeats("abcabc")"abcabc"
removeAdjRepeats("aaaa")"a"
removeAdjRepeats("abba")"aba"

Write your solution:

Solution:
public static String removeAdjRepeats(String str)
{
    String result = str.substring(0, 1);
    for (int k = 1; k < str.length(); k++)
    {
        String ch = str.substring(k, k + 1);
        String prev = str.substring(k - 1, k);
        if (!ch.equals(prev))
        {
            result += ch;
        }
    }
    return result;
}
Common Mistakes:
Starting result as empty string and beginning loop at 0 (misses the first character or adds it wrong)
Comparing to the last character of result instead of the previous character in str (different behavior for runs of 3+)
Using == instead of .equals()
PROBLEM 19

Fix an Off-by-One Loop Bug

public static int countVowels(String str)

The following method is supposed to count all vowels (a, e, i, o, u — lowercase only) in str, but it misses the last character. Find and fix the bug.

Precondition: str is not null and has length ≥ 1.

Examples:
countVowels("hello")2
countVowels("aeiou")5
countVowels("xyz")0

Write your solution:

Solution:
// BUGGY VERSION:
public static int countVowels(String str)
{
    int count = 0;
    for (int k = 0; k < str.length() - 1; k++)  // BUG: should be str.length()
    {
        String ch = str.substring(k, k + 1);
        if (ch.equals("a") || ch.equals("e") || ch.equals("i")
            || ch.equals("o") || ch.equals("u"))
        {
            count++;
        }
    }
    return count;
}

// FIXED VERSION:
public static int countVowels(String str)
{
    int count = 0;
    for (int k = 0; k < str.length(); k++)  // FIXED
    {
        String ch = str.substring(k, k + 1);
        if (ch.equals("a") || ch.equals("e") || ch.equals("i")
            || ch.equals("o") || ch.equals("u"))
        {
            count++;
        }
    }
    return count;
}
Common Mistakes:
Not recognizing that str.length() - 1 skips the last index
Confusing this with the array shifting pattern where length - 1 IS correct
Thinking the bug is in the vowel comparison logic instead of the loop bound
PROBLEM 20

Reverse a String

public static String reverse(String str)

Write a method that returns a new String that is str reversed.

Precondition: str is not null.

Examples:
reverse("hello")"olleh"
reverse("a")"a"
reverse("")""

Write your solution:

Solution:
public static String reverse(String str)
{
    String result = "";
    for (int k = str.length() - 1; k >= 0; k--)
    {
        result += str.substring(k, k + 1);
    }
    return result;
}
Common Mistakes:
Starting the loop at str.length() instead of str.length() - 1 (StringIndexOutOfBoundsException)
Using k > 0 instead of k >= 0 (misses the first character)
Building the String in the wrong direction (appending from front instead of back)
PROBLEM 21

Check if a String Contains Only Digits

public static boolean allDigits(String str)

Write a method that returns true if every character in str is a digit (0–9). An empty String returns true.

Precondition: str is not null.

Examples:
allDigits("12345")true
allDigits("12a45")false
allDigits("")true
allDigits("007")true

Write your solution:

Solution:
public static boolean allDigits(String str)
{
    for (int k = 0; k < str.length(); k++)
    {
        String ch = str.substring(k, k + 1);
        if (ch.compareTo("0") < 0 || ch.compareTo("9") > 0)
        {
            return false;
        }
    }
    return true;
}
Common Mistakes:
Returning true inside the loop (should only return true after checking ALL characters)
Using equals to check each digit individually instead of a range comparison
Forgetting that compareTo compares lexicographically, which works for single digit characters
PROBLEM 22

First Index Where Two Strings Differ

public static int firstDifference(String a, String b)

Write a method that returns the index of the first position where a and b have different characters. If one String is a prefix of the other, return the length of the shorter String. If they are identical, return -1.

Precondition: a and b are not null.

Examples:
firstDifference("hello", "help")3
firstDifference("abc", "abcdef")3
firstDifference("same", "same")-1
firstDifference("", "x")0

Write your solution:

Solution:
public static int firstDifference(String a, String b)
{
    int minLen = Math.min(a.length(), b.length());
    for (int k = 0; k < minLen; k++)
    {
        if (!a.substring(k, k + 1).equals(b.substring(k, k + 1)))
        {
            return k;
        }
    }
    if (a.length() != b.length())
    {
        return minLen;
    }
    return -1;
}
Common Mistakes:
Not handling different-length Strings (looping to the longer length causes StringIndexOutOfBoundsException)
Returning -1 when lengths differ instead of the shorter length
Using == instead of .equals() for String character comparison

Struggling with these? Get 1-on-1 AP CSA tutoring tailored to your weak areas.

Unit 3: Class Creation

Need to review first? Start with the AP CSA class writing guide or the constructors guide.

PROBLEM 23

Write a Constructor from a Specification

public class Ticket

A Ticket object has two private fields: a String called event and a double called price. Write the constructor that takes an event name and a price, and initializes both fields. If the price is negative, set it to 0.0.

Precondition: event parameter is not null.

Examples:
new Ticket("Concert", 49.99) → event = "Concert", price = 49.99
new Ticket("Game", -10.0) → event = "Game", price = 0.0

Write your solution:

Solution:
public class Ticket
{
    private String event;
    private double price;

    public Ticket(String event, double price)
    {
        this.event = event;
        if (price < 0)
        {
            this.price = 0.0;
        }
        else
        {
            this.price = price;
        }
    }
}
Common Mistakes:
Forgetting to use this.event and this.price when parameter names match field names
Not handling the negative price guard (spec requires it)
Declaring new local variables instead of assigning to instance fields
PROBLEM 24

Write an Accessor and Mutator Pair

// Add to the BankAccount class

A BankAccount class has a private double field called balance. Write an accessor method getBalance and a mutator method deposit that adds a given amount to the balance. The deposit method should do nothing if the amount is not positive.

Precondition: The field balance already exists.

Examples:
getBalance() when balance is 100.0100.0
deposit(50.0) when balance is 100.0 → balance becomes150.0
deposit(-10.0) when balance is 100.0 → balance stays100.0

Write your solution:

Solution:
public double getBalance()
{
    return balance;
}

public void deposit(double amount)
{
    if (amount > 0)
    {
        balance += amount;
    }
}
Common Mistakes:
Making getBalance void instead of returning a double
Forgetting the guard clause for negative amounts
Using balance = amount instead of balance += amount (replaces instead of adding)
PROBLEM 25

Fix a Scope Bug

public class Player

The following constructor is supposed to initialize two fields, but it has a bug. The fields name and score remain at their default values after construction. Find and fix the bug.

Precondition: Fields private String name and private int score are declared.

Examples:
new Player("Ava", 95) → name should be "Ava", score should be 95
Bug: after construction, name is null and score is 0

Write your solution:

Solution:
// BUGGY VERSION:
public Player(String name, int score)
{
    name = name;     // assigns parameter to itself
    score = score;   // assigns parameter to itself
}

// FIXED VERSION:
public Player(String name, int score)
{
    this.name = name;
    this.score = score;
}
Common Mistakes:
Not recognizing that the parameter shadows the instance variable
Adding this. to only one field but not the other
Renaming the parameters instead of using this (works but less standard)
PROBLEM 26

Complete a toString Method

public String toString()

A Student class has private fields String name and int grade. Write a toString method that returns the format: "name (grade)". Example: "Maria (11)".

Precondition: Fields are already declared and initialized by the constructor.

Examples:
toString() when name="Maria", grade=11"Maria (11)"
toString() when name="Jake", grade=9"Jake (9)"

Write your solution:

Solution:
public String toString()
{
    return name + " (" + grade + ")";
}
Common Mistakes:
Printing instead of returning (using System.out.println)
Forgetting the space before the parenthesis
Using String.format or printf syntax instead of concatenation (not wrong, but uncommon on AP)
PROBLEM 27

Modify Object State from a Condition

public void applyDiscount(double pct)

A Product class has a private double price field. Write applyDiscount which reduces the price by the given percentage. If pct is not between 0 and 100 (exclusive), do nothing.

Precondition: price field is already declared and positive.

Examples:
applyDiscount(20.0) when price is 50.0 → price becomes40.0
applyDiscount(0.0) when price is 50.0 → price stays50.0
applyDiscount(110.0) when price is 50.0 → price stays50.0

Write your solution:

Solution:
public void applyDiscount(double pct)
{
    if (pct > 0 && pct < 100)
    {
        price -= price * pct / 100;
    }
}
Common Mistakes:
Using price * pct instead of price * pct / 100 (forgets to convert percentage)
Not guarding against pct <= 0 or pct >= 100
Returning a value instead of modifying the field (method is void)
PROBLEM 28

Write a Boolean Method from a Spec

public boolean isExpired(int currentYear)

A Membership class has a private int expirationYear field. Write isExpired which returns true if currentYear is strictly greater than expirationYear.

Precondition: expirationYear is already declared and initialized.

Examples:
isExpired(2026) when expirationYear is 2025true
isExpired(2025) when expirationYear is 2025false
isExpired(2024) when expirationYear is 2025false

Write your solution:

Solution:
public boolean isExpired(int currentYear)
{
    return currentYear > expirationYear;
}
Common Mistakes:
Using >= instead of > (the year of expiration is still valid per spec)
Using an if/else to return true/false instead of returning the expression directly (not wrong, but verbose)
Comparing to a hardcoded year instead of the parameter
PROBLEM 29

Fix a Mutator Bug

public void setTemperature(double temp)

The following mutator is supposed to update the instance variable temperature, but it has a bug. After calling setTemperature(72.0), the field is unchanged. Find and fix it.

Precondition: Field private double temperature is declared.

Examples:
setTemperature(72.0) should set temperature to 72.0
Bug: temperature remains at its old value after the call

Write your solution:

Solution:
// BUGGY VERSION:
public void setTemperature(double temp)
{
    double temperature = temp;  // creates a local variable
}

// FIXED VERSION:
public void setTemperature(double temp)
{
    temperature = temp;  // assigns to the instance variable
}
Common Mistakes:
Not recognizing that 'double temperature' creates a new local variable
Confusing this bug with the this. shadow bug (different issue)
Adding a return statement (method is void)

Need More Practice Like This?

Build a custom AP CSA test focused on your weak areas, or jump into real College Board FRQs.

Need More Practice Like This?

Build a custom AP CSA test focused on your weak areas, or jump into real College Board FRQs.

Unit 4: Arrays

Arrays appear in FRQ 3 (Array/ArrayList) every year. Need to review first? Start with the AP CSA array traversal guide or the array initialization guide.

PROBLEM 30

Count Elements Meeting a Condition

public static int countMatches(int[] data, int target)

Write a method that returns the number of elements in data that are greater than target.

Precondition: data is not null and has at least one element.

Examples:
countMatches(new int[]{3, 7, 2, 9, 5}, 4)3
countMatches(new int[]{1, 1, 1}, 5)0
countMatches(new int[]{10, 20, 30}, 0)3

Write your solution:

Solution:
public static int countMatches(int[] data, int target)
{
    int count = 0;
    for (int val : data)
    {
        if (val > target)
        {
            count++;
        }
    }
    return count;
}
Common Mistakes:
Using >= instead of > (read the spec carefully)
Returning inside the loop instead of after it
Forgetting to initialize count to 0
PROBLEM 31

Index of the Largest Value

public static int maxIndex(int[] vals)

Write a method that returns the index of the largest element in vals. If there are ties, return the index of the first occurrence.

Precondition: vals is not null and has at least one element.

Examples:
maxIndex(new int[]{3, 9, 1, 9, 5})1
maxIndex(new int[]{7})0
maxIndex(new int[]{-2, -5, -1, -3})2

Write your solution:

Solution:
public static int maxIndex(int[] vals)
{
    int idx = 0;
    for (int k = 1; k < vals.length; k++)
    {
        if (vals[k] > vals[idx])
        {
            idx = k;
        }
    }
    return idx;
}
Common Mistakes:
Starting loop at 0 instead of 1 (works but wastes a comparison)
Storing the max value but forgetting to track the index
Using >= which returns last occurrence instead of first
PROBLEM 32

Shift Elements Left

public static void shiftLeft(int[] arr)

Write a method that shifts every element in arr one position to the left. The first element is removed and the last position is filled with 0.

Precondition: arr is not null and has at least one element.

Examples:
shiftLeft(new int[]{1, 2, 3, 4, 5}) → arr becomes{2, 3, 4, 5, 0}
shiftLeft(new int[]{7}) → arr becomes{0}

Write your solution:

Solution:
public static void shiftLeft(int[] arr)
{
    for (int k = 0; k < arr.length - 1; k++)
    {
        arr[k] = arr[k + 1];
    }
    arr[arr.length - 1] = 0;
}
Common Mistakes:
Looping to arr.length instead of arr.length - 1 (ArrayIndexOutOfBoundsException)
Forgetting to set the last element to 0
Shifting right instead of left (copying in wrong direction)

Unit 4: ArrayList

ArrayList appears in FRQ 3 every year. Need to review first? Start with the AP CSA ArrayList basics guide or the removing while iterating guide.

PROBLEM 33

Filter Array into ArrayList

public static ArrayList filterAbove(int[] source, int cutoff)

Write a method that returns a new ArrayList containing only the elements from source that are strictly greater than cutoff, in their original order.

Precondition: source is not null.

Examples:
filterAbove(new int[]{3, 7, 2, 9, 5}, 4)[7, 9, 5]
filterAbove(new int[]{1, 2, 3}, 10)[]

Write your solution:

Solution:
public static ArrayList filterAbove(int[] source, int cutoff)
{
    ArrayList result = new ArrayList();
    for (int val : source)
    {
        if (val > cutoff)
        {
            result.add(val);
        }
    }
    return result;
}
Common Mistakes:
Forgetting to create the ArrayList before the loop
Using add(index, val) instead of add(val)
Returning null instead of an empty ArrayList when no matches
PROBLEM 34

Remove Below Threshold

public static void removeLow(ArrayList nums, int threshold)

Write a method that removes all elements from nums that are less than threshold.

Precondition: nums is not null.

Examples:
removeLow([3, 7, 2, 9, 1], 4) → nums becomes[7, 9]
removeLow([10, 20, 30], 5) → nums becomes[10, 20, 30]

Write your solution:

Solution:
public static void removeLow(ArrayList nums, int threshold)
{
    int k = 0;
    while (k < nums.size())
    {
        if (nums.get(k) < threshold)
        {
            nums.remove(k);
        }
        else
        {
            k++;
        }
    }
}
Common Mistakes:
Using a for loop with k++ on every iteration (skips elements after removal)
Using a for-each loop (ConcurrentModificationException)
Checking <= instead of < (read the spec)
PROBLEM 35

Check for Duplicates

public static boolean hasDuplicates(ArrayList items)

Write a method that returns true if any element appears more than once in items.

Precondition: items is not null. Elements are not null.

Examples:
hasDuplicates(["cat", "dog", "cat"])true
hasDuplicates(["red", "blue", "green"])false
hasDuplicates(["one"])false

Write your solution:

Solution:
public static boolean hasDuplicates(ArrayList items)
{
    for (int j = 0; j < items.size(); j++)
    {
        for (int k = j + 1; k < items.size(); k++)
        {
            if (items.get(j).equals(items.get(k)))
            {
                return true;
            }
        }
    }
    return false;
}
Common Mistakes:
Using == instead of .equals() for String comparison
Starting inner loop at 0 instead of j + 1 (compares element to itself)
Returning false inside the loop instead of after both loops finish
PROBLEM 36

Remove Adjacent Duplicates

public static void removeAdjDups(ArrayList words)

Write a method that removes consecutive duplicate elements from words. After the method runs, no two adjacent elements should be equal.

Precondition: words is not null. Elements are not null.

Examples:
removeAdjDups(["a", "a", "b", "b", "b", "a"]) → words becomes["a", "b", "a"]
removeAdjDups(["x", "y", "z"]) → words becomes["x", "y", "z"]

Write your solution:

Solution:
public static void removeAdjDups(ArrayList words)
{
    int k = 0;
    while (k < words.size() - 1)
    {
        if (words.get(k).equals(words.get(k + 1)))
        {
            words.remove(k + 1);
        }
        else
        {
            k++;
        }
    }
}
Common Mistakes:
Incrementing k after every removal (skips the next comparison)
Using a for loop that increments unconditionally
Comparing with == instead of .equals()
PROBLEM 37

Insert into Sorted List

public static void insertSorted(ArrayList sorted, int val)

Write a method that inserts val into the correct position in sorted so that the list remains in ascending order.

Precondition: sorted is not null and is already sorted in ascending order.

Examples:
insertSorted([1, 3, 5, 7], 4) → sorted becomes[1, 3, 4, 5, 7]
insertSorted([2, 4, 6], 9) → sorted becomes[2, 4, 6, 9]
insertSorted([5, 10], 1) → sorted becomes[1, 5, 10]

Write your solution:

Solution:
public static void insertSorted(ArrayList sorted, int val)
{
    int k = 0;
    while (k < sorted.size() && sorted.get(k) < val)
    {
        k++;
    }
    sorted.add(k, val);
}
Common Mistakes:
Forgetting the k < sorted.size() bound check (IndexOutOfBoundsException when val is largest)
Using add(val) instead of add(k, val) (always appends to end)
Using <= instead of < in the comparison (changes behavior for equal values)

Unit 4: 2D Arrays

2D Arrays appear in FRQ 4 every year. Need to review first? Start with the AP CSA 2D arrays guide or the 2D array patterns guide.

PROBLEM 38

Row with the Largest Sum

public static int maxRowIndex(int[][] grid)

Write a method that returns the index of the row with the largest sum in grid. If there are ties, return the index of the first such row.

Precondition: grid is not null and has at least one row. Each row has at least one element.

Examples:
maxRowIndex({{1, 2, 3}, {9, 0, 1}, {4, 4, 4}})1
maxRowIndex({{5}, {5}, {5}})0

Write your solution:

Solution:
public static int maxRowIndex(int[][] grid)
{
    int bestRow = 0;
    int bestSum = 0;
    for (int c = 0; c < grid[0].length; c++)
    {
        bestSum += grid[0][c];
    }
    for (int r = 1; r < grid.length; r++)
    {
        int sum = 0;
        for (int c = 0; c < grid[r].length; c++)
        {
            sum += grid[r][c];
        }
        if (sum > bestSum)
        {
            bestSum = sum;
            bestRow = r;
        }
    }
    return bestRow;
}
Common Mistakes:
Initializing bestSum to 0 instead of the actual sum of row 0 (fails with all-negative rows)
Returning the sum instead of the row index
Using >= in comparison (returns last tie instead of first)
PROBLEM 39

Count Matching Neighbors

public static int countNeighbors(int[][] grid, int row, int col, int target)

Write a method that returns the number of neighbors (up, down, left, right — not diagonal) of the cell at [row][col] that equal target. Do not count the cell itself. Handle edges correctly.

Precondition: grid is not null. row and col are valid indices in grid.

Examples:
countNeighbors({{1, 2, 1}, {2, 1, 2}, {1, 2, 1}}, 1, 1, 2)4
countNeighbors({{1, 2, 1}, {2, 1, 2}, {1, 2, 1}}, 0, 0, 2)1

Write your solution:

Solution:
public static int countNeighbors(int[][] grid, int row, int col, int target)
{
    int count = 0;
    if (row > 0 && grid[row - 1][col] == target)
        count++;
    if (row < grid.length - 1 && grid[row + 1][col] == target)
        count++;
    if (col > 0 && grid[row][col - 1] == target)
        count++;
    if (col < grid[row].length - 1 && grid[row][col + 1] == target)
        count++;
    return count;
}
Common Mistakes:
ArrayIndexOutOfBoundsException from not checking boundaries
Counting the cell itself as a neighbor
Including diagonal neighbors when the spec says up/down/left/right only
PROBLEM 40

Replace All Occurrences

public static void replaceAll(int[][] grid, int oldVal, int newVal)

Write a method that replaces every occurrence of oldVal in grid with newVal.

Precondition: grid is not null.

Examples:
replaceAll({{1, 2, 3}, {2, 1, 2}}, 2, 9) → grid becomes{{1, 9, 3}, {9, 1, 9}}
replaceAll({{5, 5}, {5, 5}}, 5, 0) → grid becomes{{0, 0}, {0, 0}}

Write your solution:

Solution:
public static void replaceAll(int[][] grid, int oldVal, int newVal)
{
    for (int r = 0; r < grid.length; r++)
    {
        for (int c = 0; c < grid[r].length; c++)
        {
            if (grid[r][c] == oldVal)
            {
                grid[r][c] = newVal;
            }
        }
    }
}
Common Mistakes:
Using grid[0].length for all rows instead of grid[r].length (fails for jagged arrays)
Returning a new array instead of modifying the existing one (method is void)
PROBLEM 41

Rows Containing a Target

public static int countRowsWithTarget(int[][] grid, int target)

Write a method that returns the number of rows in grid that contain at least one occurrence of target.

Precondition: grid is not null.

Examples:
countRowsWithTarget({{1, 2}, {3, 4}, {2, 5}}, 2)2
countRowsWithTarget({{1, 1}, {1, 1}}, 9)0

Write your solution:

Solution:
public static int countRowsWithTarget(int[][] grid, int target)
{
    int count = 0;
    for (int r = 0; r < grid.length; r++)
    {
        boolean found = false;
        for (int c = 0; c < grid[r].length; c++)
        {
            if (grid[r][c] == target)
            {
                found = true;
            }
        }
        if (found)
        {
            count++;
        }
    }
    return count;
}
Common Mistakes:
Counting every cell match instead of each row once
Forgetting to reset the found flag for each new row
Breaking out of the inner loop but forgetting to increment count

Keep Practicing

These problems are just the start. Build a full 42-question simulation or work through real College Board FRQs.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

tanner@apcsexamprep.com

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at tanner@apcsexamprep.com