AP® Computer Science A Class Creation FRQ
Work through AP Computer Science A free-response questions on Class Creation, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: Writing Classes Clear filter
Question 32
Question 33
Question 34
A fitness app records daily exercise sessions for one user. You will implement a class FitnessTracker that stores a rolling log of the user's most recent workouts and reports summary statistics. The class will be used like this.
FitnessTracker ft = new FitnessTracker(7); // track the last 7 sessions
ft.logSession(30, 4.2); // 30 minutes, 4.2 kilometers
ft.logSession(45, 6.0);
ft.logSession(20, 2.5);
double avgPace = ft.averagePace(); // minutes per kilometer
int active = ft.activeDays(25); // sessions of at least 25 minutes
A FitnessTracker must meet the following specifications.
| Method / Constructor Header | Description |
|---|---|
public FitnessTracker(int capacity) |
Creates a tracker that retains at most capacity of the most recently logged sessions. The tracker begins with no logged sessions. You may assume capacity > 0. |
public void logSession(int minutes, double kilometers) |
Records a single workout session. If the tracker already holds capacity sessions, the oldest logged session is discarded before the new session is added. minutes is always > 0 and kilometers is always > 0.0. |
public int sessionCount() |
Returns the number of sessions currently stored (always between 0 and capacity). |
public double averagePace() |
Returns the average pace (minutes per kilometer) across all currently stored sessions, computed as (total minutes) / (total kilometers) using double arithmetic. If no sessions are stored, returns 0.0. |
public int activeDays(int minMinutes) |
Returns the number of currently stored sessions whose duration is greater than or equal to minMinutes. |
Write the complete FitnessTracker class. Your implementation must meet all specifications and conform to the example. You may define additional private fields, constructors, and helper methods as needed. You may use any ArrayList- or array-based approach.
Main Solution
Sample Solution:
public class FitnessTracker
{
private int capacity;
private ArrayList<Integer> minutesLog;
private ArrayList<Double> kmLog;
public FitnessTracker(int cap)
{
capacity = cap;
minutesLog = new ArrayList<Integer>();
kmLog = new ArrayList<Double>();
}
public void logSession(int minutes, double kilometers)
{
if (minutesLog.size() == capacity) // evict oldest first
{
minutesLog.remove(0);
kmLog.remove(0);
}
minutesLog.add(minutes);
kmLog.add(kilometers);
}
public int sessionCount()
{
return minutesLog.size();
}
public double averagePace()
{
if (minutesLog.size() == 0) return 0.0;
int totalMin = 0;
double totalKm = 0.0;
for (int i = 0; i < minutesLog.size(); i++)
{
totalMin += minutesLog.get(i);
totalKm += kmLog.get(i);
}
return totalMin / totalKm; // double division
}
public int activeDays(int minMinutes)
{
int count = 0;
for (int i = 0; i < minutesLog.size(); i++)
{
if (minutesLog.get(i) >= minMinutes) count++;
}
return count;
}
}
Rubric (9 pts): class declaration + private state (1); constructor initializes all fields with empty log (1); logSession adds (1); logSession correctly discards oldest when at capacity (1); sessionCount (1); averagePace handles the empty case (1); averagePace sums and divides using double arithmetic (1); activeDays iterates all stored sessions using >= (1); overall Java class structure / visibility consistent (1).
Answer images
Question 35
A small community library uses a single rack to display books available for checkout. The rack has a fixed physical capacity, and books sit on the rack in a definite left-to-right order. Patrons interact with the rack through four operations, and a librarian wants a LibraryRack class that supports them directly.
Books are identified by their titles, represented as String values. Two books with the same title are considered the same book — the rack never contains duplicate titles. Positions on the rack are 1-based: the leftmost book is at position 1.
Write the complete LibraryRack class. Your implementation must include the instance variables needed to support the behavior and the constructor and methods described below.
Class Specification
| Member | Description |
|---|---|
public LibraryRack(int capacity) | Constructs an empty rack with the given maximum capacity. You may assume capacity >= 1. |
public boolean addBook(String title) | Adds title to the right end of the rack and returns true. If the rack is already full, or a book with the same title is already on the rack, the method makes no change and returns false. |
public String checkOut(int pos) | Removes and returns the title at 1-based position pos. Books to the right of pos shift one position to the left to close the gap. If pos is not a valid position on the rack (including when the rack is empty), the method makes no change and returns null. |
public boolean moveToFront(String title) | If title is on the rack, removes it from its current position, inserts it at position 1 (all other books keeping their relative order), and returns true. If title is not on the rack, the method makes no change and returns false. |
public int count() | Returns the number of books currently on the rack. |
Example
Consider the following sequence of calls on LibraryRack r = new LibraryRack(4);
| Call | Returns | Rack afterward (left → right) |
|---|---|---|
r.addBook("Emma") | true | Emma |
r.addBook("Dune") | true | Emma, Dune |
r.addBook("1984") | true | Emma, Dune, 1984 |
r.addBook("Dune") | false | Emma, Dune, 1984 |
r.moveToFront("1984") | true | 1984, Emma, Dune |
r.checkOut(2) | "Emma" | 1984, Dune |
r.checkOut(5) | null | 1984, Dune |
r.count() | 2 | 1984, Dune |
Constraints
- You must declare and use instance variables consistent with the behaviors above.
- You must not use any
StringorArrayListmethods that are not in the AP Java Quick Reference. - Write the entire class, including necessary
importstatements if any.
Main Solution
Sample Solution
import java.util.ArrayList;
public class LibraryRack
{
private ArrayList<String> books;
private int capacity;
public LibraryRack(int capacity)
{
this.capacity = capacity;
books = new ArrayList<String>();
}
public boolean addBook(String title)
{
if (books.size() >= capacity)
return false;
for (int i = 0; i < books.size(); i++)
{
if (books.get(i).equals(title))
return false;
}
books.add(title);
return true;
}
public String checkOut(int pos)
{
if (pos < 1 || pos > books.size())
return null;
return books.remove(pos - 1);
}
public boolean moveToFront(String title)
{
for (int i = 0; i < books.size(); i++)
{
if (books.get(i).equals(title))
{
books.remove(i);
books.add(0, title);
return true;
}
}
return false;
}
public int count()
{
return books.size();
}
}
Scoring. A single ArrayList<String> (plus the stored capacity) satisfies all five requirements cleanly. The duplicate check inside addBook must use .equals(). checkOut must guard against pos < 1 as well as pos > size(). moveToFront must preserve order of the remaining books, which a remove(i) followed by add(0, title) does automatically.
Teacher Explanation
Education Coach Advice
Traps
Answer images
Question 36
A music teacher wants to track how students log their practice time. You will design a class PracticeLog that records each practice session's duration (in minutes) and answers summary queries.
A PracticeLog object supports the following behavior:
- When constructed, a new log has zero minutes logged, zero sessions, and a longest-session value of 0.
- The method
logSession(int minutes)records a session of the given duration. Ifminutesis less than or equal to 0, the call is ignored (nothing is updated). Otherwise, the total minutes and session count increase, and the longest-session value is updated if this session is longer than any previously recorded session. - The method
averageSession()returns the average number of minutes per recorded session, as adouble. If no sessions have been logged, the method returns0.0. - The method
getTotal()returns the total minutes logged. - The method
getCount()returns the number of logged sessions. - The method
getLongest()returns the longest single session ever logged, or 0 if none.
The following table contains a sample code execution sequence and the corresponding results.
PracticeLog log = new PracticeLog();
log.logSession(30);
log.logSession(0);
log.logSession(45);
log.logSession(20);
log.getTotal();
log.getCount();
log.getLongest();
log.averageSession();
| Statements and Expressions | Value Returned (blank if no value) | Comment |
|---|---|---|
PracticeLog log = new PracticeLog(); |
Creates a new log with totalMinutes=0, sessionCount=0, longestSession=0. | |
log.logSession(30); |
Records a 30-minute session. total=30, count=1, longest=30. | |
log.logSession(0); |
Ignored (minutes \(\leq 0\)). No fields change. total=30, count=1, longest=30. | |
log.logSession(45); |
Records a 45-minute session. total=75, count=2, longest is updated to 45. | |
log.logSession(20); |
Records a 20-minute session. total=95, count=3. Longest stays at 45 (\(20 \lt 45\)). | |
log.getTotal(); |
95 |
Returns current totalMinutes. |
log.getCount(); |
3 |
Returns current sessionCount (the ignored 0-minute call did not count). |
log.getLongest(); |
45 |
Returns the maximum single-session duration recorded so far. |
log.averageSession(); |
31.666666666666668 |
Returns 95 / 3 as a double. Multiplying by 1.0 in the computation avoids integer division. |
Write the complete PracticeLog class, including all instance variables, the constructor, and all methods described above. Your implementation must conform to all specifications and must behave correctly for all valid inputs.
Main Solution
Sample Solution
public class PracticeLog
{
private int totalMinutes;
private int sessionCount;
private int longestSession;
public PracticeLog()
{
totalMinutes = 0;
sessionCount = 0;
longestSession = 0;
}
public void logSession(int minutes)
{
if (minutes > 0)
{
totalMinutes = totalMinutes + minutes;
sessionCount = sessionCount + 1;
if (minutes > longestSession)
{
longestSession = minutes;
}
}
}
public double averageSession()
{
if (sessionCount == 0)
{
return 0.0;
}
return totalMinutes * 1.0 / sessionCount;
}
public int getTotal() { return totalMinutes; }
public int getCount() { return sessionCount; }
public int getLongest() { return longestSession; }
}
Scoring (9 pts): +1 correct private instance variables of appropriate types; +1 constructor initializes all three fields to 0; +1 logSession guards against minutes <= 0; +1 logSession updates totalMinutes and sessionCount correctly; +1 logSession updates longestSession only when the new value exceeds the current maximum; +1 averageSession handles the zero-session case (returns 0.0); +1 averageSession avoids integer division without casting; +1 getTotal, getCount, getLongest return the correct fields; +1 class compiles using only allowed constructs.
Answer images
Question 37
Question 38
A small attended car park uses a class ParkingLot to manage its operation. The lot has a fixed total number of spaces, set when the lot opens for the day. The class must support recording cars entering and leaving the lot, reporting capacity information, and reporting how many cars have been admitted across the entire shift.
A ParkingLot object keeps track of three pieces of information:
- the total number of spaces in the lot, set at construction and never changed afterward,
- the current number of cars parked in the lot,
- the total number of cars that have ever been admitted into the lot during the shift (a car that enters and later leaves still counts here).
Write the complete ParkingLot class. Your class must include the instance variables described above and the behaviors specified below. All instance variables must be private.
public ParkingLot(int spaces) — Constructs a new lot with the given number of total spaces. The number of cars currently parked and the total ever admitted are both 0. You may assume spaces > 0.
public boolean enter() — Attempts to admit one car. If the lot is full (the current count equals the total number of spaces), no instance variable changes and the method returns false. Otherwise the current count increases by 1, the total ever admitted increases by 1, and the method returns true.
public boolean leave() — Attempts to release one car. If the lot is empty (the current count is 0), no instance variable changes and the method returns false. Otherwise the current count decreases by 1 and the method returns true. The total ever admitted is never decreased by leave.
public int available() — Returns the number of spaces still free in the lot, computed from the total number of spaces and the current count.
public int served() — Returns the total number of cars that have been admitted during the shift.
public double occupancy() — Returns the fraction of the lot currently occupied, expressed as a value in the range 0.0 to 1.0. The fraction is computed as the current number of cars divided by the total number of spaces. Because spaces > 0 by construction, no division-by-zero check is required.
The table below shows a possible sequence of calls on a newly constructed ParkingLot named lot. Use this sequence to guide the design and behavior of your class.
| Statements and Expressions | Value Returned (blank if no value) | Comment |
|---|---|---|
ParkingLot lot = new ParkingLot(3); |
Creates a new lot with 3 spaces, all empty, no one served yet. | |
lot.available() |
3 |
All spaces are free. |
lot.enter() |
true |
1 car parked, served count becomes 1. |
lot.enter() |
true |
2 cars parked, served count becomes 2. |
lot.enter() |
true |
3 cars parked, served count becomes 3; lot is now full. |
lot.enter() |
false |
Lot is full; rejection does not affect any field. |
lot.available() |
0 |
No spaces remain. |
lot.occupancy() |
1.0 |
Three of three spaces are occupied. |
lot.leave() |
true |
2 cars parked; served count is unchanged. |
lot.leave() |
true |
1 car parked. |
lot.leave() |
true |
0 cars parked; lot is now empty. |
lot.leave() |
false |
Lot is already empty; rejection does not affect any field. |
lot.served() |
3 |
Total ever admitted across the shift is preserved. |
lot.occupancy() |
0.0 |
Zero of three spaces are occupied. |
Write the complete ParkingLot class, including instance variables, constructor, and all methods described above.
Main Solution
Sample Solution
public class ParkingLot
{
private int totalSpaces;
private int currentCars;
private int totalAdmitted;
public ParkingLot(int spaces)
{
totalSpaces = spaces;
currentCars = 0;
totalAdmitted = 0;
}
public boolean enter()
{
if (currentCars == totalSpaces)
{
return false;
}
currentCars = currentCars + 1;
totalAdmitted = totalAdmitted + 1;
return true;
}
public boolean leave()
{
if (currentCars == 0)
{
return false;
}
currentCars = currentCars - 1;
return true;
}
public int available()
{
return totalSpaces - currentCars;
}
public int served()
{
return totalAdmitted;
}
public double occupancy()
{
return currentCars * 1.0 / totalSpaces;
}
}
Scoring notes. Points are earned for: declaring three private instance variables of the right types and capturing spaces into the total field exactly once; initializing the current count and total admitted to 0 in the constructor; rejecting the call to enter when the lot is full and otherwise incrementing both running totals; rejecting the call to leave when the lot is empty and otherwise decrementing only the current count (not the lifetime total); returning the correct difference from available; returning the lifetime total from served; and returning a double ratio from occupancy by promoting one operand. Common errors that lose points include decrementing totalAdmitted in leave, returning true for a rejected enter or leave, and writing currentCars / totalSpaces in occupancy (integer division returns either 0 or 1).
Answer images
Question 39
Question 40
A school activity office keeps a line of students waiting to board a shuttle for an event. A BoardingLine object stores the names of students currently waiting.
A BoardingLine object is created with a maximum capacity. The class supports the following behavior:
addStudentadds a student name to the end of the line if the line is not full and the name is not already present. The method returnstrueif the name is added andfalseotherwise.boardNextremoves and returns the name at the front of the line. If the line is empty, the method returnsnull.lineSizereturns the number of students currently waiting.
The following table contains a sample code execution sequence and the corresponding results.
| Statements and Expressions | Value Returned (blank if no value) | Comment |
|---|---|---|
BoardingLine line = new BoardingLine(3); |
Creates a new line that can hold at most three students. | |
line.lineSize(); |
0 |
No students are waiting yet. |
line.boardNext(); |
null |
There is nobody to board. |
line.addStudent("Ava"); |
true |
"Ava" is added to the end of the line. |
line.addStudent("Noah"); |
true |
The line now contains "Ava", "Noah", in that order. |
line.addStudent("Ava"); |
false |
Duplicate names are not added. |
line.addStudent("Mia"); |
true |
The line reaches capacity. |
line.addStudent("Leo"); |
false |
The line is full, so "Leo" is not added. |
line.boardNext(); |
"Ava" |
The front student is removed and returned. |
line.lineSize(); |
2 |
The remaining students are "Noah" and "Mia". |
Write the complete BoardingLine class, including the constructor, instance variables, and all methods described above. Your implementation must conform to all specifications and must behave correctly for all valid inputs.
Main Solution
Sample Solution
public class BoardingLine
{
private ArrayList<String> students;
private int capacity;
public BoardingLine(int maxCapacity)
{
students = new ArrayList<String>();
capacity = maxCapacity;
}
public boolean addStudent(String name)
{
if (students.size() >= capacity)
{
return false;
}
for (int i = 0; i < students.size(); i++)
{
if (students.get(i).equals(name))
{
return false;
}
}
students.add(name);
return true;
}
public String boardNext()
{
if (students.size() == 0)
{
return null;
}
return students.remove(0);
}
public int lineSize()
{
return students.size();
}
}
Scoring (9 pts): +1 appropriate private instance variables, +1 constructor initializes line and capacity, +1 rejects additions when full, +1 rejects duplicate names, +1 adds a valid name at the end and returns true, +1 returns null when empty, +1 removes and returns the front name correctly, +1 lineSize returns the current size, +1 class compiles using only allowed constructs.
Answer images
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

