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 22
Question 23
Question 24
Question 25
Question 26
Question 27
This question involves the implementation of a vending machine system that is represented by the VendingMachine class. A VendingMachine object is created with two parameters: the price of the item in cents and the initial number of items in stock.
The VendingMachine class provides a constructor and the following methods.
purchase, which attempts a purchase and returns the change in cents, or -1 if the purchase failsrestock, which adds items to the stockgetRevenue, which returns the total revenue collected in centsgetStock, which returns the number of items remaining
The following table contains a sample code execution sequence and the corresponding results.
| STATEMENTS AND EXPRESSIONS | VALUE RETURNED | COMMENT |
|---|---|---|
VendingMachine vm = new VendingMachine(150, 3); | Price is 150 cents per item. 3 items in stock. | |
vm.getStock() | 3 | |
vm.getRevenue() | 0 | No purchases have been made. |
vm.purchase(200) | 50 | Paid 200, price is 150, change is 50. |
vm.getStock() | 2 | One item sold. |
vm.getRevenue() | 150 | Revenue from one sale. |
vm.purchase(100) | -1 | Payment of 100 is less than price of 150. |
vm.getStock() | 2 | No change, purchase failed. |
vm.purchase(150) | 0 | Exact change, no money returned. |
vm.purchase(200) | 50 | |
vm.getStock() | 0 | All items sold. |
vm.getRevenue() | 450 | Three successful purchases. |
vm.purchase(200) | -1 | Out of stock. |
vm.getStock() | 0 | |
vm.restock(2) | Two items added. | |
vm.getStock() | 2 | |
vm.purchase(175) | 25 | |
vm.getRevenue() | 600 | Four total successful purchases. |
Write the complete VendingMachine class, including the constructor and any required instance variables and methods. Your implementation must meet all specifications and conform to the example.
public class VendingMachine {
}Main Solution
Complete VendingMachine class implementation:
public class VendingMachine {
private int price;
private int stock;
private int revenue;
/**
* Constructs a VendingMachine with the given price per item
* and initial number of items in stock.
* @param itemPrice the price of one item in cents
* @param initialStock the initial number of items available
*/
public VendingMachine(int itemPrice, int initialStock) {
price = itemPrice;
stock = initialStock;
revenue = 0;
}
/**
* Attempts to purchase one item.
* Returns the change in cents if successful,
* or -1 if the purchase fails (insufficient payment or out of stock).
* @param payment the amount paid in cents
* @return change in cents, or -1 if purchase fails
*/
public int purchase(int payment) {
if (stock == 0 || payment < price) {
return -1;
}
stock--;
revenue += price;
return payment - price;
}
/**
* Adds the given number of items to the stock.
* @param numItems the number of items to add
*/
public void restock(int numItems) {
stock += numItems;
}
/**
* Returns the total revenue collected in cents.
* @return total revenue in cents
*/
public int getRevenue() {
return revenue;
}
/**
* Returns the number of items currently in stock.
* @return number of items remaining
*/
public int getStock() {
return stock;
}
}Trace through the sample execution to verify:
new VendingMachine(150, 3):price=150,stock=3,revenue=0vm.getStock()→ 3 ✓vm.getRevenue()→ 0 ✓vm.purchase(200): payment(200) ≥ price(150), stock(3) > 0 → stock becomes 2, revenue becomes 150, returns 200−150 = 50 ✓vm.getStock()→ 2 ✓vm.getRevenue()→ 150 ✓vm.purchase(100): payment(100) < price(150) → returns −1 ✓vm.getStock()→ 2 (unchanged) ✓vm.purchase(150): payment(150) ≥ price(150) → stock becomes 1, revenue becomes 300, returns 0 ✓vm.purchase(200): stock(1) > 0 → stock becomes 0, revenue becomes 450, returns 50 ✓vm.getStock()→ 0 ✓vm.getRevenue()→ 450 ✓vm.purchase(200): stock == 0 → returns −1 ✓vm.getStock()→ 0 ✓vm.restock(2): stock becomes 2 ✓vm.getStock()→ 2 ✓vm.purchase(175): payment(175) ≥ price(150) → stock becomes 1, revenue becomes 600, returns 25 ✓vm.getRevenue()→ 600 ✓
Teacher Explanation
This FRQ tests students' ability to write a complete Java class from scratch, including instance variables, a constructor, and multiple methods. Key concepts tested:
- Instance variables: Students must identify that
price,stock, andrevenueneed to be stored as private fields. - Constructor: Must accept two parameters and initialize all three instance variables (revenue starts at 0).
- purchase method: Must handle two failure cases (out of stock AND insufficient payment), update both
stockandrevenueon success, and return the correct change or −1. - restock method: Simple addition to stock; note it is
void. - Accessor methods:
getRevenue()andgetStock()are straightforward getters.
AP scoring typically awards points for: correct instance variables, correct constructor, correct purchase logic (both failure conditions, revenue update, change calculation), correct restock, and correct accessors.
Education Coach Advice
AP Exam Strategy for "Write a Complete Class" FRQs:
- Read the table carefully: The sample execution table is your specification. Trace through every row to understand exactly what each method must do.
- Identify instance variables first: Before writing any methods, ask yourself: what data must the object remember between method calls? Here: price, stock, revenue.
- Write the constructor next: Initialize all instance variables. Note which ones come from parameters vs. which start at a fixed value (revenue = 0).
- Handle all edge cases in purchase: The table explicitly shows both failure modes — insufficient payment AND out of stock. Make sure your condition covers both.
- Verify with the trace: After writing your class, mentally trace through the table rows to confirm your output matches. This catches off-by-one errors and wrong variable updates.
- Use private instance variables: Always declare instance variables as
privatein AP CSA FRQs.
Traps
Common pitfalls on this FRQ:
- Missing failure condition: Students often check only one of the two failure conditions in
purchase(e.g., only checkingpayment < pricebut forgettingstock == 0, or vice versa). - Wrong revenue update: Adding
paymentto revenue instead ofprice. Revenue should reflect the item price, not the amount paid. - Not initializing revenue to 0: Forgetting to initialize
revenue = 0in the constructor (though Java defaults int to 0, explicit initialization is best practice and may be required for full credit). - restock replacing instead of adding: Writing
stock = numItemsinstead ofstock += numItems. - Wrong return type for restock: Making
restockreturn an int instead of void. - Order of failure checks: The order of checking
stock == 0vs.payment < pricedoes not matter for correctness, but both must be present.
Question 28
A downtown parking garage charges a flat rate per hour for each car that parks. The garage has a fixed number of spaces. When a car enters, it occupies one space. When a car exits, the system calculates the charge based on the number of hours parked and adds it to the total revenue. A car cannot enter if no spaces are available. The following table shows an example sequence of operations on a ParkingGarage object.
| STATEMENTS AND EXPRESSIONS | VALUE RETURNED | COMMENT |
|---|---|---|
ParkingGarage g = new ParkingGarage(3, 5); | Three spaces, $5 per hour | |
g.getOpenSpaces() | 3 | |
g.enter() | true | Car enters successfully |
g.enter() | true | Second car enters |
g.getOpenSpaces() | 1 | |
g.enter() | true | Third car enters |
g.enter() | false | Garage is full |
g.exit(3) | 15 | Car parked 3 hours: 3 × 5 = 15 |
g.getOpenSpaces() | 1 | One space freed |
g.exit(1) | 5 | Car parked 1 hour: 1 × 5 = 5 |
g.getRevenue() | 20 | Total revenue: 15 + 5 |
Write the complete ParkingGarage class, including the constructor and any required instance variables and methods. Your implementation must meet all specifications and conform to the example.
public class ParkingGarage {Main Solution
Below is a complete, AP-aligned implementation of the ParkingGarage class.
public class ParkingGarage {
private int totalSpaces; // total number of spaces in the garage
private int openSpaces; // number of currently available spaces
private int hourlyRate; // charge per hour in dollars
private int totalRevenue; // cumulative revenue collected
/**
* Constructs a ParkingGarage with the given number of spaces
* and the given hourly rate.
*
* @param spaces the fixed total number of parking spaces
* @param ratePerHour the charge in dollars per hour
*/
public ParkingGarage(int spaces, int ratePerHour) {
totalSpaces = spaces;
openSpaces = spaces; // initially all spaces are open
hourlyRate = ratePerHour;
totalRevenue = 0;
}
/**
* Returns the number of currently open (available) spaces.
*
* @return number of open spaces
*/
public int getOpenSpaces() {
return openSpaces;
}
/**
* Attempts to admit a car into the garage.
* If at least one space is open, occupies one space and returns true.
* If the garage is full, returns false without changing state.
*
* @return true if the car successfully entered, false otherwise
*/
public boolean enter() {
if (openSpaces > 0) {
openSpaces--;
return true;
}
return false;
}
/**
* Processes a departing car that was parked for the given number of hours.
* Calculates the charge (hours * hourlyRate), adds it to total revenue,
* frees one space, and returns the charge.
*
* @param hours the number of hours the car was parked
* @return the charge for this car's stay
*/
public int exit(int hours) {
int charge = hours * hourlyRate;
totalRevenue += charge;
openSpaces++; // one space is freed when a car exits
return charge;
}
/**
* Returns the total revenue collected so far.
*
* @return cumulative revenue in dollars
*/
public int getRevenue() {
return totalRevenue;
}
}
Trace through the example to verify correctness:
| Statement | Expected | Result with implementation |
|---|---|---|
new ParkingGarage(3, 5) | — | totalSpaces=3, openSpaces=3, hourlyRate=5, totalRevenue=0 |
g.getOpenSpaces() | 3 | openSpaces=3 ✓ |
g.enter() | true | openSpaces becomes 2, returns true ✓ |
g.enter() | true | openSpaces becomes 1, returns true ✓ |
g.getOpenSpaces() | 1 | openSpaces=1 ✓ |
g.enter() | true | openSpaces becomes 0, returns true ✓ |
g.enter() | false | openSpaces=0, returns false ✓ |
g.exit(3) | 15 | charge=3×5=15, totalRevenue=15, openSpaces=1, returns 15 ✓ |
g.getOpenSpaces() | 1 | openSpaces=1 ✓ |
g.exit(1) | 5 | charge=1×5=5, totalRevenue=20, openSpaces=2, returns 5 ✓ |
g.getRevenue() | 20 | totalRevenue=20 ✓ |
Teacher Explanation
This FRQ tests students' ability to design and implement a complete Java class from a behavioral specification. Key concepts assessed:
- Instance variables: Students must identify the four pieces of state needed — total spaces, open spaces, hourly rate, and accumulated revenue.
- Constructor: Must initialize all instance variables;
openSpacesstarts equal tototalSpaces. - enter(): Guard condition (
openSpaces > 0) before decrementing; returns boolean. - exit(int hours): Multiplies hours by rate, accumulates revenue, increments
openSpaces, returns the charge. - getOpenSpaces() / getRevenue(): Simple accessor methods.
Award full credit for any implementation that produces the correct values shown in the table. Minor style issues (e.g., using double instead of int) should not be penalized if the logic is correct.
Education Coach Advice
AP Exam Strategy for class-design FRQs:
- Read the table of operations carefully — each row tells you exactly what method signature and return type you need.
- List all instance variables first before writing any methods; ask yourself "what state does this object need to remember?"
- Trace through the example table with your implementation before finalizing — it is the built-in test case.
- Keep methods short and focused; each method should do exactly one thing.
- You earn partial credit for each correct method, so write all methods even if one is incomplete.
Traps
Common pitfalls on this FRQ:
- Forgetting to increment openSpaces in exit(): Students often calculate and return the charge correctly but forget to free the space, causing
getOpenSpaces()to return the wrong value afterward. - Not accumulating revenue: Returning
hours * hourlyRatewithout adding it tototalRevenuemeansgetRevenue()always returns 0. - Initializing openSpaces to 0: Students may forget that all spaces start open, so
openSpacesshould be initialized tototalSpaces, not 0. - enter() not returning false when full: Omitting the guard condition or always returning true fails the "Garage is full" case.
- Missing instance variables: Storing hourly rate or revenue only as local variables instead of fields causes them to be lost between method calls.
Question 29
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.

