Strings – FRQ Practice (AP Computer Science A)
Strings are an important part of Java programming and frequently appear in the AP Computer Science A FRQ section. Master these 15 original AP CSA-style FRQ practice problems featuring clean Java solutions, common pitfalls to avoid, and step-by-step logic breakdowns.
Students must know how to process characters, analyze substrings, validate formats, and build new strings safely using loops and conditions. Use this page as your ultimate practice hub to master the String class methods found on the AP Java Quick Reference guide.
Why Practice String FRQs?
- Safe substring extraction and avoiding
StringIndexOutOfBoundsException. - Counting patterns and managing sliding window boundaries.
- Validating input formats using standard subset methods.
- Scanning through characters using
indexOf()andequals(). - Building and accumulating new strings using concatenation.
AP CSA String Methods You Should Know

FRQ 1 — Count Vowels
Write a method countVowels(String s) that returns the total number of vowels (a, e, i, o, u) that appear in the parameter s. Assume s is not null. Ignore case.
“Computer” → 3
- Traverse each character using a
forloop andsubstring(). - Check membership against a constant string containing both uppercase and lowercase vowels.
public int countVowels(String s) {
int count = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (vowels.indexOf(c) != -1) {
count++;
}
}
return count;
}- Forgetting to check for uppercase vowels.
- Using
==instead ofequals()to compareStringobjects.
FRQ 2 — Remove All Digits
Write a method removeDigits(String s) that returns a new string containing all the characters of s except numerical digits.
“a1b2c3d4” → “abcd”
- Traverse the original string character by character.
- Append characters to the result string only if they are not found in a master “digits” string.
public String removeDigits(String s) {
String result = "";
String digits = "0123456789";
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (digits.indexOf(c) == -1) {
result = result + c;
}
}
return result;
}- Returning
nullinstead of an initialized empty string"". - Using non-subset methods like
Character.isDigit().
FRQ 3 — Reverse a String
Write a method reverseString(String s) that returns the string completely reversed.
“java” → “avaj”
- Traverse backwards from the last valid index (
length() - 1) down to0. - Concatenate the characters sequentially to build the reversed string.
public String reverseString(String s) {
String rev = "";
for (int i = s.length() - 1; i >= 0; i--) {
rev = rev + s.substring(i, i + 1);
}
return rev;
}- Starting the loop at
s.length()resulting in aStringIndexOutOfBoundsException. - Using
i > 0instead ofi >= 0and missing the very first character.
FRQ 4 — Count Words
Write a method countWords(String s) to return the number of words. Assume words are separated by exactly one space, there are no leading/trailing spaces, and if the string is empty it returns 0.
“AP Computer Science” → 3
- If the string is perfectly formatted with single spaces, the number of words will always be exactly one more than the number of spaces.
public int countWords(String s) {
if (s.length() == 0) return 0;
int count = 1;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals(" ")) {
count++;
}
}
return count;
}- Failing the empty string
""test case by returning1instead of0. - Using
==to compare substring equality with" ".
FRQ 5 — Find the Longest Word
Write a method longestWord(String sentence) that returns the longest word. Assume words are separated by exactly one space. If there is a tie, return the first longest word found.
“I love programming in Java” → “programming”
- Build a
currentword character by character until a space is hit. - Compare the length of
currentagainstlongest. Resetcurrentto capture the next word. - Remember to process the very last word after the loop ends.
public String longestWord(String sentence) {
String longest = "";
String current = "";
for (int i = 0; i < sentence.length(); i++) {
String c = sentence.substring(i, i + 1);
if (c.equals(" ")) {
if (current.length() > longest.length()) {
longest = current;
}
current = "";
} else {
current = current + c;
}
}
// Check the final word after the last space
if (current.length() > longest.length()) {
longest = current;
}
return longest;
}- Using
>=instead of strict>, which would incorrectly return the last tie instead of the first. - Forgetting to do a final check for the last word outside the loop.
FRQ 6 — Remove Vowels
Write a method removeVowels(String s) that removes all vowels from the string. Case should be ignored when determining what to remove.
“Computer” → “Cmptr”
- Check membership in a constant string containing uppercase and lowercase vowels via
indexOf. - If
indexOfreturns-1, the character is safe to append.
public String removeVowels(String s) {
String result = "";
String vowels = "aeiouAEIOU";
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (vowels.indexOf(c) == -1) {
result = result + c;
}
}
return result;
}- Forgetting to list uppercase vowels in the lookup string.
- Trying to remove characters without preserving the original order of the remaining characters.
FRQ 7 — Check Palindrome
Write a method isPalindrome(String s) that returns true if the string reads identically forwards and backwards, and false otherwise.
“level” → true
- Use two index pointers:
leftstarting at the beginning, andrightstarting at the end. - Compare characters, moving inward. If a mismatch is found, immediately return
false.
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (!s.substring(left, left + 1).equals(s.substring(right, right + 1))) {
return false;
}
left++;
right--;
}
return true;
}- Incorrect pointer initialization (setting right to
s.length()instead ofs.length() - 1). - Using a full reverse-and-compare method, which is less efficient than the two-pointer approach.
FRQ 8 — Count Uppercase Letters
Write a method countUppercase(String s) that returns the total count of uppercase letters in the given string.
“ApCSa” → 2
- For this AP CSA practice problem, we use
compareTo()to determine whether each one-character String falls between “A” and “Z”.
public int countUppercase(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (c.compareTo("A") >= 0 && c.compareTo("Z") <= 0) {
count++;
}
}
return count;
}- Counting lowercase letters instead
- Comparing string objects using relational operators (
>=) instead ofcompareTo().
FRQ 9 — Count Substring Occurrences
Write a method countOccurrences(String s, String sub) that counts all (including overlapping) occurrences of sub inside s. Assume sub has a length of at least 1.
“aaaa”, “aa” → 3
- Slide a window across the string and compare each substring
public int countOccurrences(String s, String sub) {
int count = 0;
int subLen = sub.length();
for (int i = 0; i <= s.length() - subLen; i++) {
if (s.substring(i, i + subLen).equals(sub)) {
count++;
}
}
return count;
}- Forgetting the
<=boundary, resulting in missing a match at the very end of the string. - Using
==instead ofequals()to compare equality.
FRQ 10 — Validate ID Format
A valid ID must be exactly 6 characters long, where the first 2 characters are strictly alphabetic letters (A-Z or a-z), followed by exactly 4 numerical digits. Return true if valid.
“AB1234” → true, “A12345” → false
- First evaluate the length condition. If invalid, fail early.
- Use lookup strings to validate positions 0-1 as letters and positions 2-5 as numbers.
public boolean isValidID(String id) {
if (id.length() != 6) return false;
String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower = "abcdefghijklmnopqrstuvwxyz";
String digits = "0123456789";
String c1 = id.substring(0, 1);
String c2 = id.substring(1, 2);
boolean isC1Letter = (upper.indexOf(c1) != -1 || lower.indexOf(c1) != -1);
boolean isC2Letter = (upper.indexOf(c2) != -1 || lower.indexOf(c2) != -1);
if (!isC1Letter || !isC2Letter) {
return false;
}
for (int i = 2; i < 6; i++) {
if (digits.indexOf(id.substring(i, i + 1)) == -1) {
return false;
}
}
return true;
}- Failing to enforce the exact string length prior to processing indices, causing bounds exceptions.
- Creating overly complex, nested
iflogic.
FRQ 11 — Remove Extra Spaces
Write a method removeExtraSpaces(String s). Assume the input contains no leading or trailing spaces. Replace every sequence of two or more consecutive spaces with a single space.
“AP Computer Science” → “AP Computer Science”
- Traverse characters and skip appending a space if the previous character was also a space
public String removeExtraSpaces(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (i == 0 || !c.equals(" ") || !s.substring(i - 1, i).equals(" ")) {
result = result + c;
}
}
return result;
}- Index out of bounds when checking previous characters
FRQ 12 — Extract Digits
Write a method extractDigits(String s) that returns a new string containing only the numerical digits from the input string in their original order.
“ab12cd34” → “1234”
- Traverse each character and append only those found in a lookup digit set (
"0123456789").
public String extractDigits(String s) {
String result = "";
String digits = "0123456789";
for (int i = 0; i < s.length(); i++) {
String c = s.substring(i, i + 1);
if (digits.indexOf(c) != -1) {
result = result + c;
}
}
return result;
}- Returning numeric types instead of a
String - Missing characters in loops
FRQ 13 — Longest Consecutive Character
Write a method longestStreak(String s) to return the character that has the longest consecutive repetition. Assume the string is non-empty. In the event of a tie, return the first character string to achieve that streak length.
“aaabbccccd” → “c”
- Track a
countof the current streak, comparingcurrcharacter toprevcharacter. - Track a
bestCountto store the maximum streak value and update it accordingly.
public String longestStreak(String s) {
if (s.length() == 0) return "";
String best = s.substring(0, 1);
int bestCount = 1;
int count = 1;
for (int i = 1; i < s.length(); i++) {
String curr = s.substring(i, i + 1);
String prev = s.substring(i - 1, i);
if (curr.equals(prev)) {
count++;
if (count > bestCount) {
bestCount = count;
best = curr;
}
} else {
count = 1;
}
}
return best;
}- Forgetting to reset the current
countback to1when the streak ends. - Starting the loop at index
0and failing bounds limits on checkingi - 1.
FRQ 14 — Compress String
Write a method compress(String s) that implements basic run-length encoding. For each group of repeating adjacent characters, append the character followed by the number of times it repeats.
“aaabbc” → “a3b2c1”
- Traverse the string from index 1 to
s.length() - 1. - Count consecutive identical characters. When the sequence breaks, append the character and its count to the result.
- Be sure to append the final character group after the loop terminates.
public String compress(String s) {
if (s.length() == 0) return "";
String result = "";
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (s.substring(i, i + 1).equals(s.substring(i - 1, i))) {
count++;
} else {
result = result + s.substring(i - 1, i) + count;
count = 1;
}
}
// Process the final group
result = result + s.substring(s.length() - 1) + count;
return result;
}- Forgetting to process and append the final character group after the loop finishes.
FRQ 15 — Mask Email Username
Write a method maskEmail(String email) that masks all characters of an email username except the very first and last characters. Assume the string contains exactly one “@” and the username length is at least 1. If username length is <= 2, return the email unchanged.
“john.doe@gmail.com” → “j******e@gmail.com”
- Use
indexOf("@")to parse the domain boundary safely. - Separate username and domain text pieces, loop to construct the central stars, and recombine.
public String maskEmail(String email) {
int at = email.indexOf("@");
String user = email.substring(0, at);
String domain = email.substring(at);
if (user.length() <= 2) return email;
String masked = user.substring(0, 1);
for (int i = 1; i < user.length() - 1; i++) {
masked = masked + "*";
}
masked = masked + user.substring(user.length() - 1);
return masked + domain;
}- Masking the domain part of the email
- Not accounting for short edge-case usernames.
Frequently Asked Questions
What String methods should I know for AP CSA?
You should master the methods listed on the official AP Java Quick Reference guide: length(), substring(), indexOf(), equals(), and compareTo().
How do I practice Strings for AP Computer Science A?
The best way is to write solutions by hand first, tracing your indices carefully on paper, and then type them up. Focus on loop bounds and avoiding out-of-bounds exceptions.
Are these official College Board FRQs?
No. These are original, custom-designed AP CSA–style practice problems created for additional practice. They are not released College Board questions.
Is substring() important for AP CSA?
Yes. You should understand both the single-parameter version and the two-parameter version.
How should I approach a String question on the AP CSA exam?
Read the problem carefully, clarify assumptions (like empty strings or spaces), draw out a concrete example with indices, and decide whether a for loop or a while loop is best for traversing the characters.
FRQ Strategy Tips for Strings (AP CSA)
- Always clarify assumptions before coding.
- Prefer index-based loops over enhanced for-loops when dealing with complex substrings.
- Use standard String concatenation or approved subset methods.
- Watch loop boundaries carefully to avoid
StringIndexOutOfBoundsException. - Write clear, logically structured solutions and check each part of the question against the requirements.
Related FRQ Pages
- Arrays – FRQ Practice
- ArrayList – FRQ Practice
- 2D Arrays – FRQ Practice
- Classes & Objects – FRQ Practice
- Mixed FRQs
- Mock FRQ Sets
Need Structured Help With AP Computer Science A?
If you want guided, one-on-one support for AP Computer Science A—including FRQs, MCQs, debugging, and exam strategy—you can explore my private AP CSA online tutoring program.
Ideal for students targeting a score of 4 or 5 on the AP CSA exam.
WhatsApp: +91 9853166385
Email: javatution@gmail.com
Book a free demo: Contact Chinmay