What this quiz covers
This quiz focuses on Documentation With Comments, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
public class Wallet { private double balance;
/**
* Adds money to the wallet.
* Precondition: amount > 0
* Postcondition: balance is increased by amount.
*/
public void addMoney(double amount)
{
balance = amount;
}
// ... constructor not shown
}
The implementation of the addMoney method is incorrect because it does not meet its postcondition. Why?
balance variable should be a public instance variable.setMoney instead of addMoney.amount to balance instead of adding to it.amount > 0 is not checked inside the method.AP Computer Science a Quiz
Practice Documentation With Comments in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.
This quiz focuses on Documentation With Comments, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.
public class Wallet { private double balance;
/**
* Adds money to the wallet.
* Precondition: amount > 0
* Postcondition: balance is increased by amount.
*/
public void addMoney(double amount)
{
balance = amount;
}
// ... constructor not shown
}
The implementation of the addMoney method is incorrect because it does not meet its postcondition. Why?
balance variable should be a public instance variable.setMoney instead of addMoney.amount to balance instead of adding to it. (correct answer)amount > 0 is not checked inside the method.Explanation: The postcondition states that the balance is increased by amount. The code balance = amount; sets the balance equal to the amount, overwriting the previous value. The correct implementation would be balance += amount; or balance = balance + amount;. Therefore, the implementation fails to meet the specified postcondition.
/**
The setScore method is intended to update an instance variable named score. Why does this implementation fail to meet its documented postcondition?
newScore shadows the instance variable score.score instead of assigning to the instance variable. (correct answer)newScore is positive.Explanation: The line int score = newScore; declares a new local variable named score that exists only within the method. It does not affect the instance variable of the same name. To meet the postcondition, the line should be this.score = newScore; or simply score = newScore; (without the type declaration int).
/**
The precondition 'The player's current position is valid' is documented for the movePlayer method. Why is this statement considered a precondition?
numSpaces parameter.Explanation: A precondition is a requirement on the state of the program or the method's inputs that must be met before the method is invoked. This statement concerns the player's position prior to the move, making it a classic example of a precondition.
/**
The documentation for getFirstChar states that word should be a non-empty string. Which of the following is an additional, unstated precondition required to prevent a run-time error?
word parameter must have a length greater than 1.word parameter must not be null. (correct answer)word parameter must not contain any spaces.Explanation: If the word parameter is null, the call word.charAt(0) will result in a NullPointerException. The documented precondition 'non-empty' ensures the length is greater than 0, but it does not prevent a null value from being passed. Therefore, word not being null is a necessary, unstated precondition.
/**
Consider the provided calculateArea method. Which of the following statements best describes a precondition for this method?
width and height parameters must represent positive values. (correct answer)width and height parameters must be of type int.width and height parameters.Explanation: A precondition is a condition that must be true before a method is called for it to work as intended. The comment explicitly states 'Precondition: width > 0 and height > 0', which means the parameters must be positive values. Choice B describes a postcondition (what is true after the method runs). Choice C contradicts the method signature, which specifies double parameters. Choice D describes the implementation details, not a condition for the method's use.
/**
was equal to target, the new element at words.get(i)
is equal to replacement.
/ public void replaceAll(ArrayList words, String target, String replacement) { / implementation not shown */ }
Based on the postcondition provided in the documentation, what is guaranteed to be true after a call to replaceAll?
words list will contain at least one instance of the replacement string.words list will no longer contain any instances of the target string. (correct answer)words list will remain unchanged.words list will be sorted alphabetically.Explanation: The postcondition states that every element that was equal to target is now equal to replacement. This implies that after the method executes, no elements equal to target will remain. Choice A is not guaranteed; if target was not in the list originally, replacement will not be added. Choice C is an implicit postcondition but not the one explicitly described. Choice D is incorrect; the method only replaces elements and does not sort them.
A programmer is writing documentation for a method that sorts an ArrayList of String objects in alphabetical order.
public void sortStrings(ArrayList<String> list)
Which of the following would be an appropriate postcondition to include in the documentation for the sortStrings method?
list parameter is not null.list are arranged in non-decreasing alphabetical order. (correct answer)list parameter contains at least one String object.Explanation: A postcondition describes the state after the method completes. Since the method's purpose is to sort the list, the statement that the list's elements are in sorted order is a direct and essential postcondition. Choices A and D describe preconditions that should be true before the method is called. Choice C describes an implementation detail, which is not part of the contract defined by postconditions.
In the StudentRecord code below, what information do the inline comments provide in this program?
import java.util.ArrayList;
import java.util.List;
/**
* Maintains quiz scores and computes an average.
* Demonstrates how inline comments can justify small design choices.
*/
public class StudentRecord {
private final List<Integer> quizScores = new ArrayList<>();
/**
* Adds a quiz score from 0 to 10.
*
* @param score the quiz score
* @return true if the score is stored
*/
public boolean addQuizScore(int score) {
if (score < 0 || score > 10) {
// Enforce the stated scale so the average remains interpretable.
return false;
}
quizScores.add(score);
return true;
}
/**
* Computes the arithmetic mean of stored quiz scores.
*
* @return the average, or 0.0 if no scores exist
*/
public double averageScore() {
if (quizScores.isEmpty()) {
// Avoid dividing by zero when no scores have been added.
return 0.0;
}
int sum = 0;
for (int score : quizScores) {
// Accumulate the total to compute the mean in one pass.
sum += score;
}
return (double) sum / quizScores.size();
}
}
Explanation: This question tests AP Computer Science A documentation with comments, specifically understanding how inline comments provide implementation details and justify design choices. Inline comments within methods explain specific logic decisions and help prevent common programming errors. In this StudentRecord code, the inline comments justify the 0-10 score validation, explain why empty list checking prevents division by zero, and clarify the accumulation logic in the averaging calculation. Choice A is correct because the comments justify validation logic and explain why special cases like empty lists need safeguards to prevent runtime errors. Choice B is incorrect because comments are not executable commands - they cannot control program flow or prevent loops from running. When teaching inline comments, encourage students to document edge cases and explain any non-obvious logic. Show how comments can serve as reminders about why certain checks are necessary, preventing future maintainers from accidentally removing important safeguards.
In the LibraryManager code below, what is the purpose of the comments in the provided code snippet?
import java.util.HashSet;
import java.util.Set;
/**
* Tracks a set of unique book titles for a small library catalog.
* Comments illustrate why specific validations are performed.
*/
public class LibraryManager {
private final Set<String> titles = new HashSet<>();
/**
* Adds a title to the catalog.
*
* @param title the title to add
* @return true if the catalog changed
*/
public boolean addBook(String title) {
if (title == null) {
// Null titles provide no searchable value.
return false;
}
String normalized = title.trim();
if (normalized.isEmpty()) {
// Blank strings are rejected to avoid cluttering the catalog.
return false;
}
return titles.add(normalized);
}
/**
* Determines whether a title exists in the catalog.
*
* @param title the title to check
* @return true if present; false otherwise
*/
public boolean contains(String title) {
if (title == null) {
return false;
}
// Trim to treat leading/trailing spaces as insignificant.
return titles.contains(title.trim());
}
}
Explanation: This question tests AP Computer Science A documentation with comments, specifically understanding how comments explain validation logic and design decisions. Comments provide crucial context for understanding why certain checks and normalizations are performed in code. In this LibraryManager code, comments explain why null titles are rejected, why blank strings are filtered out, and why trimming is used for normalization - all decisions that make the catalog more robust and consistent. Choice A is correct because the comments explain validation and normalization decisions, making future changes safer by documenting the reasoning behind each check. Choice C is incorrect because comments are not executable - the Set's duplicate rejection is a feature of the HashSet data structure, not the comments. When teaching comment writing, have students explain their validation logic in comments, focusing on the business reasons behind technical decisions. This practice helps maintain code quality when requirements change.
Refer to this StudentRecord code snippet: ```java import java.util.ArrayList; import java.util.List;
/**
Maintains grades and computes a simple GPA. */ public class StudentRecord { private final List grades = new ArrayList<>();
/**
/**
Computes GPA on a 4.0 scale.
@return GPA, or 0.0 if no grades */ public double calculateGpa() { if (grades.isEmpty()) { return 0.0; }
double sum = 0.0; for (double g : grades) { sum += g; }
double average = sum / grades.size(); // Linear conversion keeps the example straightforward. return (average / 100.0) * 4.0; } }
Explanation: This question tests AP Computer Science A documentation with comments, specifically identifying the function of Javadoc comments in providing structured API documentation. Javadoc comments use a standardized format with special tags (@param, @return) to document method signatures, making code self-documenting and enabling automatic documentation generation. In the StudentRecord code, Javadoc comments describe each method's purpose, document parameters including their expected ranges (0 to 100 for grades), and specify return values like the GPA calculation result or the special case of returning 0.0 when no grades exist. Choice A is correct because it identifies that Javadoc comments provide structured documentation that formally describes parameters and return values, creating a clear contract for method usage. Choice C is incorrect because comments cannot execute or clamp values - the actual Math.min/max code performs the clamping, while comments only explain what happens. To teach this concept, show students how IDEs use Javadoc comments to display method information in tooltips and how documentation generators create HTML documentation from these comments. Emphasize the importance of keeping Javadoc comments synchronized with code changes.
In the SimpleCalculator code below, what information do the inline comments provide in this program?
/**
* Performs basic arithmetic operations.
* Emphasizes documentation with Javadoc and inline comments.
*/
public class SimpleCalculator {
/**
* Adds two numbers.
*
* @param a first operand
* @param b second operand
* @return the sum of a and b
*/
public double add(double a, double b) {
return a + b;
}
/**
* Subtracts one number from another.
*
* @param a first operand
* @param b second operand
* @return the result of a minus b
*/
public double subtract(double a, double b) {
return a - b;
}
/**
* Multiplies two numbers.
*
* @param a first operand
* @param b second operand
* @return the product of a and b
*/
public double multiply(double a, double b) {
return a * b;
}
/**
* Divides one number by another.
*
* @param numerator value to be divided
* @param denominator value to divide by
* @return the quotient
* @throws IllegalArgumentException if denominator is zero
*/
public double divide(double numerator, double denominator) {
if (denominator == 0) {
// Division by zero is undefined, so we fail fast with a clear message.
throw new IllegalArgumentException("denominator must not be zero");
}
// Use direct division; no rounding is applied in this educational example.
return numerator / denominator;
}
}
Explanation: This question tests AP Computer Science A documentation with comments, specifically understanding the purpose of inline comments within method implementations. Inline comments are single-line (//) or multi-line (/* */) comments that explain specific code logic within methods. In this SimpleCalculator code, the inline comments explain why certain checks are performed (like division by zero) and clarify implementation choices (like not applying rounding). Choice A is correct because the inline comments describe why exceptions are thrown for division by zero and explain the division logic implementation details. Choice B is incorrect because comments cannot optimize performance or instruct the JVM - they are completely removed during compilation. To teach inline comments effectively, encourage students to write comments that explain complex logic or non-obvious decisions. Emphasize that inline comments should add value by explaining 'why' something is done, not just restating what the code already shows.
In the BankAccount code below, what information do the inline comments provide in this program?
/**
* Demonstrates a bank account with a simple transfer operation.
*/
public class BankAccount {
private double balance;
/**
* Creates an account with a starting balance.
*
* @param startingBalance initial funds
*/
public BankAccount(double startingBalance) {
this.balance = startingBalance;
}
/**
* Transfers money from this account to another account.
*
* @param other the destination account
* @param amount the amount to transfer
* @return true if the transfer succeeds
*/
public boolean transferTo(BankAccount other, double amount) {
if (other == null || amount <= 0) {
// Invalid destination or amount: do not change either account.
return false;
}
// Withdraw first; only deposit if withdrawal succeeds to avoid partial transfers.
if (!withdraw(amount)) {
return false;
}
other.deposit(amount);
return true;
}
/**
* Deposits money into the account.
*
* @param amount the amount to add
*/
public void deposit(double amount) {
if (amount <= 0) {
return;
}
balance += amount;
}
/**
* Withdraws money from the account.
*
* @param amount the amount to remove
* @return true if successful
*/
public boolean withdraw(double amount) {
if (amount <= 0 || balance < amount) {
return false;
}
balance -= amount;
return true;
}
}
Explanation: This question tests AP Computer Science A documentation with comments, specifically understanding how inline comments explain complex operation logic and maintain data consistency. Comments are essential for documenting multi-step operations where the order of operations matters. In this BankAccount code, the inline comments explain validation checks, document why the withdrawal must happen before the deposit to avoid partial transfers, and clarify the logic for maintaining consistent account states. Choice A is correct because the comments explain why validation and operation ordering prevent inconsistent state during transfers, helping future developers understand the critical sequence. Choice B is incorrect because comments cannot cause runtime behavior like atomic locking - they are purely documentation with no executable effect. To teach this concept, have students identify operations where order matters and write comments explaining why steps must occur in a specific sequence. This practice is especially important for operations that modify multiple objects.
/**
Consider the provided findMax method. Which of the following is a postcondition of the method?
nums must not be empty.nums array. (correct answer)nums.nums is not modified during the execution of the method.Explanation: A postcondition describes the state of the program or the value returned after a method has executed. The @return tag documents the primary postcondition, stating that the method returns the largest integer value in nums. Choice A is the precondition. Choice C describes a possible implementation, not a guaranteed outcome. While choice D is also a valid postcondition (the method does not have side effects on the array), choice B describes the main purpose and return value, which is the most direct postcondition.
A programmer wants to add documentation to a Java method that can be processed by the Javadoc tool to generate API documentation. Which comment syntax must be used?
// A single-line comment/* A block comment */# A comment/** A Javadoc comment */ (correct answer)Explanation: The Javadoc tool specifically processes comments that begin with /** and end with */. Standard single-line (//) and block (/* */) comments are ignored by the Javadoc tool. The # symbol is used for comments in other languages, such as Python, not Java.
public void processItem(Item anItem) { anItem.updatePrice(); // ... more code }
Consider the processItem method, which takes an Item object as a parameter. Which of the following is the most critical implicit precondition for this method to avoid a NullPointerException?
Item class must have a public updatePrice method.anItem parameter must not be null. (correct answer)updatePrice method must not change the item's name.processItem method must be called from within the Item class.Explanation: The line anItem.updatePrice() attempts to call a method on the anItem object. If anItem is a null reference, this will cause a NullPointerException at run-time. Therefore, a critical precondition is that anItem must refer to an actual Item object and not be null. Choice A is checked by the compiler. Choice C is a postcondition of updatePrice, not a precondition of processItem. Choice D is not required.
/**
Consider the call getPrefix(myArray, 5), where myArray is an integer array of length 10. Which statement about this method call is true?
n is not 0.n is less than source.length.source is not empty.Explanation: The precondition is 0 <= n <= source.length. In this call, n is 5 and source.length is 10. The condition evaluates to 0 <= 5 <= 10, which is true. Therefore, the precondition is satisfied.
public int getSum(int[] data) { int total = 0; for(int x : data) { total += x; } return total; }
A programmer adds documentation to the getSum method. Which of the following is NOT a valid postcondition for this method, assuming its preconditions are met?
data is not modified.data.data is not empty. (correct answer)Explanation: A postcondition is a statement that is true after the method runs. Choices A, B, and C all describe the result and side effects (or lack thereof) of the method. Choice D, which states that the input array is not empty, is a condition that must be true before the method is called to ensure correct behavior in some contexts. It is a precondition, not a postcondition. (Note: this method actually works correctly for an empty array, returning 0).
/**
What information does the @param tag provide in a Javadoc comment?
Explanation: The @param tag is used in Javadoc comments to document each parameter that a method takes. It typically includes the parameter's name and a brief description of its purpose. The @return tag describes the return value.
/**
Which of the following is a necessary, implicit precondition for the hasSameArea method to avoid a NullPointerException?
other parameter must not be null. (correct answer)Rectangle other must have a positive width and height.true.Rectangle object must have the same width as other.Explanation: Inside the method, code will likely need to access the properties of the other rectangle (e.g., other.getWidth()). If other is null, any such access will cause a NullPointerException. Therefore, ensuring other is not null is a crucial precondition, even if not explicitly stated in the documentation.
/**
Which of the following is the most important precondition to add to the documentation for the factorial method to ensure it works as intended and avoids unintended behavior like infinite loops or incorrect results?
n is an integer.n >= 0. (correct answer)int.Explanation: The factorial function is mathematically defined for non-negative integers. If n is negative, the standard factorial algorithm would not terminate correctly. Therefore, n >= 0 is a critical precondition for the method's logic. Choice A is enforced by the compiler. Choice B is a postcondition. Choice D is a valid concern about overflow, but the fundamental mathematical domain of the function is the most essential precondition.