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.
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: low ≤ high.
clamp(5, 1, 10) → 5
clamp(-3, 1, 10) → 1
clamp(15, 1, 10) → 10
Write your solution:
public static int clamp(int val, int low, int high)
{
return Math.min(Math.max(val, low), high);
}
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.
sameStart("hello", "happy") → true
sameStart("abc", "xyz") → false
Write your 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));
}
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.
applyOperations(4) → 4
applyOperations(10) → 2
applyOperations(0) → 3
Write your solution:
public static int applyOperations(int x)
{
x *= 2;
x += 3;
return x % 7;
}
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.
middleThree("abcdefg") → "cde"
middleThree("abcde") → "bcd"
middleThree("ab") → "ab"
middleThree("a") → "a"
Write your 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);
}
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: low ≤ high.
randomInRange(1, 6) → returns a value from 1 to 6 inclusiverandomInRange(0, 0) → always returns → 0
Write your solution:
public static int randomInRange(int low, int high)
{
return (int)(Math.random() * (high - low + 1)) + low;
}
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.
average(3, 4) → 3.5
average(5, 5) → 5.0
average(1, 2) → 1.5
Write your 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;
}
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.
truncatedAvg(1, 2, 4) → 2
truncatedAvg(10, 10, 10) → 10
truncatedAvg(1, 1, 2) → 1
Write your solution:
public static int truncatedAvg(int a, int b, int c)
{
return (a + b + c) / 3;
}
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 @.
getDomain("student@school.edu") → "school.edu"
getDomain("a@b.com") → "b.com"
Write your solution:
public static String getDomain(String email)
{
int atIndex = email.indexOf("@");
return email.substring(atIndex + 1);
}
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.
digitCount(1234) → 4
digitCount(0) → 1
digitCount(-57) → 2
digitCount(9) → 1
Write your 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;
}
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.
rollDie() should return 1, 2, 3, 4, 5, or 6Bug: currently returns 0, 1, 2, 3, 4, or 5Write your 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
}
Unit 2: Selection and Iteration
Need to review first? Start with the AP CSA loops guide or the String methods guide.
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.
countSubs("abcabc", "abc") → 2
countSubs("aaaa", "aa") → 3
countSubs("hello", "xyz") → 0
Write your 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;
}
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.
everyNth("abcdefgh", 3) → "adg"
everyNth("Hello", 1) → "Hello"
everyNth("abcdef", 2) → "ace"
Write your 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;
}
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.
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:
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;
}
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: low ≤ high.
inRange(5, 1, 10) → true
inRange(1, 1, 10) → true
inRange(11, 1, 10) → false
Write your solution:
public static boolean inRange(int val, int low, int high)
{
return val >= low && val <= high;
}
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.
firstDuplicate("abcab") → 0
firstDuplicate("abcde") → -1
firstDuplicate("xyzxw") → 0
firstDuplicate("aabb") → 0
Write your 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;
}
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.
isPalindrome("racecar") → true
isPalindrome("hello") → false
isPalindrome("a") → true
isPalindrome("Aba") → false
Write your 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;
}
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.
firstUpper("helloWorld") → 5
firstUpper("alllower") → -1
firstUpper("ABC") → 0
Write your 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;
}
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.
removeAdjRepeats("aabbcc") → "abc"
removeAdjRepeats("abcabc") → "abcabc"
removeAdjRepeats("aaaa") → "a"
removeAdjRepeats("abba") → "aba"
Write your 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;
}
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.
countVowels("hello") → 2
countVowels("aeiou") → 5
countVowels("xyz") → 0
Write your 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;
}
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.
reverse("hello") → "olleh"
reverse("a") → "a"
reverse("") → ""
Write your 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;
}
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.
allDigits("12345") → true
allDigits("12a45") → false
allDigits("") → true
allDigits("007") → true
Write your 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;
}
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.
firstDifference("hello", "help") → 3
firstDifference("abc", "abcdef") → 3
firstDifference("same", "same") → -1
firstDifference("", "x") → 0
Write your 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;
}
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.
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.
new Ticket("Concert", 49.99) → event = "Concert", price = 49.99new Ticket("Game", -10.0) → event = "Game", price = 0.0Write your 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;
}
}
}
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.
getBalance() when balance is 100.0 → 100.0
deposit(50.0) when balance is 100.0 → balance becomes → 150.0
deposit(-10.0) when balance is 100.0 → balance stays → 100.0
Write your solution:
public double getBalance()
{
return balance;
}
public void deposit(double amount)
{
if (amount > 0)
{
balance += amount;
}
}
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.
new Player("Ava", 95) → name should be "Ava", score should be 95Bug: after construction, name is null and score is 0Write your 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;
}
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.
toString() when name="Maria", grade=11 → "Maria (11)"
toString() when name="Jake", grade=9 → "Jake (9)"
Write your solution:
public String toString()
{
return name + " (" + grade + ")";
}
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.
applyDiscount(20.0) when price is 50.0 → price becomes → 40.0
applyDiscount(0.0) when price is 50.0 → price stays → 50.0
applyDiscount(110.0) when price is 50.0 → price stays → 50.0
Write your solution:
public void applyDiscount(double pct)
{
if (pct > 0 && pct < 100)
{
price -= price * pct / 100;
}
}
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.
isExpired(2026) when expirationYear is 2025 → true
isExpired(2025) when expirationYear is 2025 → false
isExpired(2024) when expirationYear is 2025 → false
Write your solution:
public boolean isExpired(int currentYear)
{
return currentYear > expirationYear;
}
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.
setTemperature(72.0) should set temperature to 72.0Bug: temperature remains at its old value after the callWrite your 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
}
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.
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.
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:
public static int countMatches(int[] data, int target)
{
int count = 0;
for (int val : data)
{
if (val > target)
{
count++;
}
}
return count;
}
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.
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:
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;
}
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.
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:
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;
}
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.
Filter Array into ArrayList
public static ArrayListfilterAbove(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.
filterAbove(new int[]{3, 7, 2, 9, 5}, 4) → [7, 9, 5]
filterAbove(new int[]{1, 2, 3}, 10) → []
Write your solution:
public static ArrayListfilterAbove(int[] source, int cutoff) { ArrayList result = new ArrayList (); for (int val : source) { if (val > cutoff) { result.add(val); } } return result; }
Remove Below Threshold
public static void removeLow(ArrayListnums, int threshold)
Write a method that removes all elements from nums that are less than threshold.
Precondition: nums is not null.
removeLow([3, 7, 2, 9, 1], 4) → nums becomes → [7, 9]
removeLow([10, 20, 30], 5) → nums becomes → [10, 20, 30]
Write your solution:
public static void removeLow(ArrayListnums, int threshold) { int k = 0; while (k < nums.size()) { if (nums.get(k) < threshold) { nums.remove(k); } else { k++; } } }
Check for Duplicates
public static boolean hasDuplicates(ArrayListitems)
Write a method that returns true if any element appears more than once in items.
Precondition: items is not null. Elements are not null.
hasDuplicates(["cat", "dog", "cat"]) → true
hasDuplicates(["red", "blue", "green"]) → false
hasDuplicates(["one"]) → false
Write your solution:
public static boolean hasDuplicates(ArrayListitems) { 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; }
Remove Adjacent Duplicates
public static void removeAdjDups(ArrayListwords)
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.
removeAdjDups(["a", "a", "b", "b", "b", "a"]) → words becomes → ["a", "b", "a"]
removeAdjDups(["x", "y", "z"]) → words becomes → ["x", "y", "z"]
Write your solution:
public static void removeAdjDups(ArrayListwords) { int k = 0; while (k < words.size() - 1) { if (words.get(k).equals(words.get(k + 1))) { words.remove(k + 1); } else { k++; } } }
Insert into Sorted List
public static void insertSorted(ArrayListsorted, 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.
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:
public static void insertSorted(ArrayListsorted, int val) { int k = 0; while (k < sorted.size() && sorted.get(k) < val) { k++; } sorted.add(k, val); }
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.
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.
maxRowIndex({{1, 2, 3}, {9, 0, 1}, {4, 4, 4}}) → 1
maxRowIndex({{5}, {5}, {5}}) → 0
Write your 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;
}
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.
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:
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;
}
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.
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:
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;
}
}
}
}
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.
countRowsWithTarget({{1, 2}, {3, 4}, {2, 5}}, 2) → 2
countRowsWithTarget({{1, 1}, {1, 1}}, 9) → 0
Write your 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;
}
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
tanner@apcsexamprep.com
Courses
AP CSA, CSP, & Cybersecurity
Response Time
Within 24 hours
Prefer email? Reach me directly at tanner@apcsexamprep.com