FRQ Type 1: Methods and Control Structures
Practice these in the app
The first free-response question on the AP Computer Science A exam gives you part of a class and asks for two pieces of it: a method or a constructor in part (a), and a method in part (b) that often calls part (a). Most years the class arrives with a method already written, called the helper, that your code must call. The parts loop over a range, run a simulation until something happens, or search a String and build a new one.
It is always the first of the exam's four free-response questions, worth 7 of their 25 points: 4 for part (a) and 3 for part (b).
The helper
The class arrives with methods whose bodies say "implementation not shown," and the directions name the one you must use to receive full credit. You never write the helper. You call it, trust what it returns, and build your answer around that value. Code of your own that does the helper's job, even correct code, does not earn the point for calling it.
The examples on this page use a class for a planetarium that runs shows numbered 1 through
getNumShows():public class Planetarium
{
/** Returns the number of visitors seated for show, always >= 0
* Precondition: 1 <= show <= getNumShows() */
public int visitorsAt(int show)
{ /* implementation not shown */ }
/** Seats as many people from the waiting line for show as the dome
* has room for, and returns how many were seated
* Precondition: 1 <= show <= getNumShows() */
public int admitLine(int show)
{ /* implementation not shown */ }
/** Returns the number of shows, always > 0 */
public int getNumShows()
{ /* implementation not shown */ }
}Some helpers only report, like
visitorsAt. Others change the data, like admitLine, which seats people and returns how many. Call a helper that changes data exactly once for each pass through the loop, store what it returns, and use the stored value as often as you need:int seated = admitLine(show);
total += seated;
if (seated == 0)
{
emptyLines++;
}Calling
admitLine(show) again in the if would seat another group, and the number it returns could differ from the one added to the total. In 2025, a response that called the part (a) method more than once inside the loop of part (b) lost the algorithm point, because each call changed the company's records. A helper that only reports can be called twice without harm, but a stored value is easier to read either way.Often the helper's value can't be used as it comes. It may be -1 for "not found," more than a limit allows, or a change that would take an amount below 0. Store the value, test it, and only then act on it:
int show = firstShowWith(crowd);
if (show != -1)
{
int counted = visitorsAt(show);
if (counted > 50)
{
counted = 50;
}
total += counted;
}Points in 2017, 2023, 2024, and 2025 checked exactly this: a test for a missing result before the next call, a cap at a maximum, and an amount kept from going below 0. A response that called the next helper with -1, or used the uncapped value, lost the point.
Part (b) often calls the method you wrote in part (a). Assume part (a) works as its comment describes, even if your part (a) is wrong or blank, and call it. From 2021 through 2025, every question whose part (b) needed the part (a) method had a point for calling it correctly.
Counted loops
Many parts loop over a range the question gives, such as from
first to last, inclusive. The loop variable starts at the first value, the test uses <=, and the total starts before the loop and is returned after it:public int totalAdmitted(int first, int last)
{
int total = 0;
for (int show = first; show <= last; show++)
{
total += admitLine(show);
}
return total;
}Finding the best of several values works the same way, with a variable that holds the best so far. Starting it at the first show, not at 0, means the answer is always a real show number:
public int busiestShow(int first, int last)
{
int best = first;
for (int show = first + 1; show <= last; show++)
{
if (visitorsAt(show) > visitorsAt(best))
{
best = show;
}
}
return best;
}With
>, a tie keeps the earlier show; with >=, it takes the later one. When a question says which one to return on a tie, that choice is often where a point is checked. Some questions ask for a count instead: start it at 0 before the loop and add 1 inside an if.Loops that stop on a condition
When the number of passes isn't known in advance, the loop runs until something happens: a value is found, a supply runs out, or a limit is reached. A search can return the moment it finds what it needs, as long as the "not found" answer comes after the loop:
public int firstShowWith(int crowd)
{
int show = 1;
while (show <= getNumShows())
{
if (visitorsAt(show) >= crowd)
{
return show;
}
show++;
}
return -1;
}A return inside a loop is fine when the answer is already known. It is wrong when the method stops before checking everything the answer depends on. The classic case puts
else return -1; inside the loop, so the method gives up after the first show it checks.Some parts track a run, such as the longest stretch of shows in a row that were full. Keep a counter for the current run, add 1 when the run continues, and set it back to 0 when it breaks. A response that never resets the counter loses the algorithm point.
Searching a String
The String parts have asked students to count a word inside a String, to remove characters, to replace part of it, and to rebuild it letter by letter. The String methods on the exam's Java Quick Reference are enough for all of these:
length(), substring(from, to), substring(from), indexOf(str), equals(other), compareTo(other), and split(del).A common pattern finds a match, counts it, and then searches only the part of the String after it. The amount you cut off decides whether matches may overlap. In
"lalala", the pattern "lala" starts at index 0 and again at index 2, so the two matches share two letters:public static int countFinds(String text, String target)
{
int count = 0;
String rest = text;
int at = rest.indexOf(target);
while (at >= 0)
{
count++;
rest = rest.substring(at + 1);
at = rest.indexOf(target);
}
return count;
}Cutting off one character past the start,
at + 1, finds both matches and returns 2. Cutting off the whole match, at + target.length(), skips the second one and returns 1. Read the question to see which one it wants. A question that counts overlapping matches takes a point from a response that skips them, and one that says matches don't overlap allows either cut.A loop over every position is the other way to search. The window
text.substring(i, i + target.length()) must end inside the String, so the loop runs while i + target.length() <= text.length(). Running i all the way to text.length() reaches past the end and throws a StringIndexOutOfBoundsException, which the guides score as a bounds error. Compare the window with equals, never ==.Building a String
To build a new String, start with
"" and add each piece that belongs. This method keeps only the digits of a ticket code, so "A7-B21-C4" gives "7214":public static String digitsOnly(String code)
{
String result = "";
for (int i = 0; i < code.length(); i++)
{
String ch = code.substring(i, i + 1);
if ("0123456789".indexOf(ch) >= 0)
{
result += ch;
}
}
return result;
}The test
"0123456789".indexOf(ch) >= 0 asks whether the character is one of the ten digits, without ten separate comparisons.To take pieces out instead, work on a copy and rebuild it around each piece:
copy = copy.substring(0, at) + copy.substring(at + piece.length()); Use a copy because a part (b) method usually comes with a postcondition that the instance variable is unchanged. In 2026, a response that shortened username itself, instead of a local copy, lost the algorithm point.Arithmetic: % and /, casts, and random numbers
Integer arithmetic shows up in part (a) as often as in part (b). For an
int n, n % 10 is its last digit and n / 10 drops that digit, so a loop that looks at n % 10 and then divides by 10 until n is 0 visits every digit. Counting the digits greater than 5 that way, 4073 gives 1. Check the edge case the question names: that loop never runs when n is 0, which is fine for this count but wrong for a question that counts every digit, where 0 has one.- Counting around in a circle uses
%: with 5 projectors numbered 0 through 4 taking turns, the projector 3 turns after projector 4 is(4 + 3) % 5, which is 2. - Dividing two
intvalues throws away the fraction, so3 / 4is 0. For a proportion, cast first:(double) 3 / 4is 0.75. - A random
intfrommintomax, inclusive, is(int) (Math.random() * (max - min + 1)) + min. From 5 to 12 that is(int) (Math.random() * 8) + 5. - An event with a 30% chance happens when
Math.random() < 0.3.
Scoring notes
- Each part has one point marked algorithm. It needs every step of the part, joined in the right order. The other points each check one thing and can be earned next to mistakes elsewhere.
- The algorithm point can survive a mistake that another point already charges. In 2026, a constructor that checked availability the wrong way could still earn it.
- Since 2026 there are no separate penalty deductions. Through 2025, a list of penalties could take up to 3 points off a question. Now most of those errors, plus one new one, cost the algorithm point of the part where they appear: printing that wasn't asked for,
[]wheregetis needed, changing data that should stay the same, returning a value from avoidmethod or a constructor, and, new in 2026, rewriting the given header with a different number or type of parameters. - Return the answer. A method that prints its result instead of returning it, or as well as returning it, loses the point that checks the result.
- A constructor sets instance variables. Every path through it has to give the variable its value, including the case where no loop is needed at all.
- Small slips are ignored: spelling or capitals that leave no doubt, a missing semicolon or brace where the indentation shows the structure,
lengthwritten forsize, a local variable used without being declared, and different parameter names in the header. - Write something for every step. A loop with a wrong bound still earns the points for the call and the total inside it.
Common traps
- An inclusive range written with
<, which drops the last value. A range fromfirsttolastneeds<=. - Calling a helper that changes data twice in one pass. Store its result once.
- An
ifand anelsethat both return inside the loop, so the loop never gets past its first pass. - A total or count set to 0 inside the loop, so it starts over on every pass. Start it before the loop.
- A count that starts at the wrong value. In 2026 the numbers added to a name began at 1, and a count that started at 0 lost the algorithm point.
- Skipping overlapping matches when the question counts them, or counting the same match twice.
- Comparing Strings with
==instead ofequals, or using the result ofcompareToas if it weretrueorfalse. - Reaching past the end of a String with
substring, often in the last pass of a loop. - Calling a String method and throwing away its result, as in
word.substring(1);on its own line. - Changing an instance variable that the postcondition says stays the same, instead of a local copy.
- Dividing two
intvalues when the answer is a fraction. - Forgetting the case that needs no loop at all, such as a name that is already available.
- Two separate
ifstatements for a rule that pays once when either condition holds, which pays twice when both do. Use oneifwith||. A rule that pays a later level only when every earlier one was reached needs nestedifstatements or&&.
A full question
Part (a) offers orders until
count of them have been taken, stepping next around the row with %:public int assignOrders(int count)
{
int last = next;
int given = 0;
while (given < count)
{
if (isClean(next))
{
last = next;
given++;
}
next = (next + 1) % numBlenders();
}
return last;
}The number of passes isn't known in advance, because skipped blenders take a pass without taking an order, so the loop counts orders given, not blenders visited. A
for loop that runs count times would hand out fewer orders whenever it met a blender that isn't clean. The step (next + 1) % numBlenders() takes the last blender back to 0; without it, isClean is called with a blender that doesn't exist. And last is saved before next goes up, because after the step next already names the following blender, which is what the instance variable should hold when the method ends.Part (b) copies each name's first three letters and a slash, cutting a local copy,
rest, after each slash, so menu stays unchanged:public String shortMenu()
{
String rest = menu;
String result = "";
int slash = rest.indexOf("/");
while (slash >= 0)
{
result += rest.substring(0, 3) + "/";
rest = rest.substring(slash + 1);
slash = rest.indexOf("/");
}
result += rest.substring(0, 3);
return result;
}The last name has no slash after it, so the loop ends before reaching it, and the line after the loop adds it. A response without that line returns
"Lyc/Pap/Gua/". Cutting menu itself instead of a copy breaks the postcondition.A scoring guide for this question, written in the style of the 2026 guidelines, could read:
| Point | Earned for | Notes |
|---|---|---|
| A1 | Calls isClean with an int blender number | Earned even if the result isn't used; not earned for a call on another object |
| A2 | Steps through the blenders from next, going back to 0 after the last one | Not earned if a blender number past the last is ever used |
| A3 | Counts an order only for a clean blender | Earned even if the loop stops at the wrong time |
| A4 (algorithm) | Hands out exactly count orders, returns the blender that took the last one, and leaves next on the blender after it | Not earned for a loop that runs count times, for a wrong next at the end, or for printing the answer |
| B1 | Considers several parts of menu inside a loop | Earned even if a String method is called incorrectly |
| B2 | Identifies the location of a slash in menu, and every String call is valid | Earned with indexOf or by comparing one-character substrings; not earned if the location found is never stored or used |
| B3 (algorithm) | Returns the correct short menu, including the last name | Not earned for a bounds error, for changing menu, or for printing the result |
Here is the whole class as a program. On the exam the two helpers' bodies are not shown; here they read an array so the program can run. Press Run, then make another blender unclean, start at a different blender, or change the menu. Keep at least one blender clean: with none, the loop in part (a) never ends, which is why the precondition rules it out.
public class Main
{
public static void main(String[] args)
{
// Blenders 0 through 3; blender 2 is not clean
boolean[] clean = {true, true, false, true};
SmoothieBar bar = new SmoothieBar(clean, 1, "Lychee/Papaya/Guava/Tamarind");
System.out.println("3 orders, last at blender " + bar.assignOrders(3));
System.out.println("1 order, last at blender " + bar.assignOrders(1));
System.out.println("5 orders, last at blender " + bar.assignOrders(5));
System.out.println("Short menu: " + bar.shortMenu());
}
}
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.
Released exam index
Every released question of this type, 2010 to 2026. The ones before 2019 come from exams that did not yet give the question types a fixed order; each one fits this type in what it asks.
| Exam | Class | Key features |
|---|---|---|
| 2014 Q1 | Static String methods | (a) rebuild a word, swapping an "A" with a following letter that is not an "A" and skipping past each swap; (b) works on a list |
| 2016 Q2 | LogMessage | Constructor splits a message at its colon with indexOf and substring; a whole-word search with checks at both ends; (c) works on a list |
| 2017 Q1 | Digits | Constructor puts the digits of a number into an ArrayList with % and /, with 0 as a special case; then checks that the digits increase |
| 2017 Q3 | Phrase | Replace the nth occurrence of a word using a provided search helper; find the last occurrence with repeated calls to that helper |
| 2018 Q1 | FrogSimulation | Simulation loop around a provided hop helper, stopping at the goal, below 0, or after the last hop; a proportion as a double |
| 2019 Q1 | APCalendar | Static helpers; count leap years over an inclusive range; day of the week with % |
| 2021 Q1 | WordMatch | Count overlapping occurrences and score by length; compare two scores, breaking a tie with compareTo |
| 2022 Q1 | Game, Level | Points from nested checks of three levels, tripled in a bonus game; the best score over several plays, calling play once each pass |
| 2023 Q1 | AppointmentBook | First block of free minutes through a helper, resetting the run at each busy minute; search several periods, then reserve |
| 2024 Q1 | Feeder | Random simulation with a rare event, food never below 0; repeat for several days and stop early |
| 2025 Q1 | DogWalker, DogWalkCompany | Cap a helper's value at a maximum and update the company; total pay over an hour range with a bonus, calling part (a) once each hour |
| 2026 Q1 | Account | Constructor appends 1, 2, 3, and so on to a name until a helper says it is available; remove each hyphen and the character before it |