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.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.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./**
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.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.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.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.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();
}
}
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());
}
}
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; } }
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;
}
}
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;
}
}
/**
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.@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)/** 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.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.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)/**
What information does the @param tag provide in a Javadoc comment?
@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.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.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.