AP Computer Science a Quiz: Documentation With Comments
20 questions · exam conditions
0:00
Documentation With CommentsQuestion 1 of 20

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?

The balance variable should be a public instance variable.
The method should be named setMoney instead of addMoney.
The method assigns amount to balance instead of adding to it.
The precondition amount > 0 is not checked inside the method.
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Documentation With Comments

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.

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.

How to use this quiz

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.

All questions

Question 1

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?

  1. The balance variable should be a public instance variable.
  2. The method should be named setMoney instead of addMoney.
  3. The method assigns amount to balance instead of adding to it. (correct answer)
  4. The precondition 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.

Question 2

/**

  • Sets the score for a student.
  • Postcondition: The student's score is updated to newScore.
  • @param newScore the student's new score */ public void setScore(int newScore) { int score = newScore; }

The setScore method is intended to update an instance variable named score. Why does this implementation fail to meet its documented postcondition?

  1. The parameter newScore shadows the instance variable score.
  2. The method declares a new local variable score instead of assigning to the instance variable. (correct answer)
  3. The method should return the new score to confirm it has been set.
  4. A precondition is missing to check if 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).

Question 3

/**

  • Moves a player on a game board.
  • Precondition: The player's current position is valid.
  • @param numSpaces the number of spaces to move / public void movePlayer(int numSpaces) { / ... */ }

The precondition 'The player's current position is valid' is documented for the movePlayer method. Why is this statement considered a precondition?

  1. It describes the state of the player object after the method has finished executing.
  2. It describes a condition related to the object's state that must be true before the method is called. (correct answer)
  3. It describes the purpose of the numSpaces parameter.
  4. It describes the value that will be returned by the method.

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.

Question 4

/**

  • Returns the first character of a given string.
  • @param word a non-empty string
  • @return the first character of word */ public char getFirstChar(String word) { return word.charAt(0); }

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?

  1. The word parameter must have a length greater than 1.
  2. The word parameter must not be null. (correct answer)
  3. The method must return a lowercase character.
  4. The 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.

Question 5

/**

  • Calculates the area of a rectangle.
  • @param width the width of the rectangle
  • @param height the height of the rectangle
  • Precondition: width > 0 and height > 0
  • @return the area of the rectangle / public double calculateArea(double width, double height) { / implementation not shown */ }

Consider the provided calculateArea method. Which of the following statements best describes a precondition for this method?

  1. The width and height parameters must represent positive values. (correct answer)
  2. The method must return a positive value representing the area.
  3. The width and height parameters must be of type int.
  4. The area is determined by multiplying the 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.

Question 6

/**

  • Replaces all occurrences of a target word with a replacement word.
  • @param words The list of words to be processed.
  • @param target The word to be replaced.
  • @param replacement The word to substitute for the target.
  • Postcondition: For every index i, if the original element at words.get(i)
  •            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?

  1. The words list will contain at least one instance of the replacement string.
  2. The words list will no longer contain any instances of the target string. (correct answer)
  3. The size of the words list will remain unchanged.
  4. The 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.

Question 7

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?

  1. The list parameter is not null.
  2. The elements of list are arranged in non-decreasing alphabetical order. (correct answer)
  3. The method uses an efficient sorting algorithm to reorder the list.
  4. The 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.

Question 8

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();
    }
}
  1. They justify validation and explain why special cases, like empty lists, need safeguards. (correct answer)
  2. They are executable commands that prevent the loop from running when scores are low.
  3. They increase numerical precision by forcing integer sums to be stored as doubles.
  4. They are decorative and cannot help a future programmer understand the method's behavior.

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.

Question 9

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());
    }
}
  1. They explain validation and normalization decisions, making future changes safer and clearer. (correct answer)
  2. They encrypt the stored titles so only authorized users can read the catalog.
  3. They function as executable checks that the Set uses to reject duplicates automatically.
  4. They improve performance by allowing the compiler to skip trimming operations at runtime.

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.

Question 10

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<>();

    /**

    • Adds a grade to the record.
    • @param grade value from 0 to 100 */ public void addGrade(double grade) { // Clamp values to keep calculations within an expected range. double clamped = Math.min(100.0, Math.max(0.0, grade)); grades.add(clamped); }

    /**

    • 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; } }

  1. They provide structured documentation for methods, describing parameters and return values. (correct answer)
  2. They act as decorative headers, adding style but no meaningful information.
  3. They execute before methods, clamping grades to keep values within range.
  4. They replace unit tests by guaranteeing GPA correctness through compiler checks.

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.

Question 11

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;
    }
}
  1. They describe why exceptions are thrown and how the division logic is handled. (correct answer)
  2. They optimize division speed by instructing the JVM to skip safety checks.
  3. They act as executable statements that change the divide method's returned value.
  4. They are required syntax for compilation whenever an if statement appears.

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.

Question 12

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;
    }
}
  1. They explain why validation and operation ordering prevent inconsistent state during transfers. (correct answer)
  2. They cause transferTo to run atomically by locking both accounts at runtime.
  3. They replace the withdraw method by instructing Java to skip subtraction operations.
  4. They primarily exist to fix syntax errors that would otherwise appear in transferTo.

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.

Question 13

/**

  • Finds the maximum value in an array of integers.
  • Precondition: nums.length > 0
  • @param nums the array of integers to search
  • @return the largest integer value in nums / public int findMax(int[] nums) { / implementation not shown */ }

Consider the provided findMax method. Which of the following is a postcondition of the method?

  1. The array nums must not be empty.
  2. The method returns the largest integer value found within the nums array. (correct answer)
  3. The method must use a loop to iterate through every element of nums.
  4. The array 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.

Question 14

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?

  1. // A single-line comment
  2. /* A block comment */
  3. # A comment
  4. /** 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.

Question 15

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?

  1. The Item class must have a public updatePrice method.
  2. The anItem parameter must not be null. (correct answer)
  3. The updatePrice method must not change the item's name.
  4. The 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.

Question 16

/**

  • Returns a new array containing the first n elements of the source array.
  • Precondition: 0 <= n <= source.length
  • @param source the original array
  • @param n the number of elements to copy
  • @return a new array with the first n elements / public int[] getPrefix(int[] source, int n) { / implementation not shown */ }

Consider the call getPrefix(myArray, 5), where myArray is an integer array of length 10. Which statement about this method call is true?

  1. The call violates the precondition because n is not 0.
  2. The call violates the precondition because n is less than source.length.
  3. The call satisfies the precondition. (correct answer)
  4. The call violates the precondition because 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.

Question 17

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?

  1. The method returns an integer value.
  2. The input array data is not modified.
  3. The returned value is the sum of the elements in data.
  4. The input array 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).

Question 18

/**

  • ... (description of method)
  • @param index the position to access
  • @return the element at the given index */

What information does the @param tag provide in a Javadoc comment?

  1. It describes the value returned by the method.
  2. It indicates the author of the method.
  3. It specifies a condition that must be true before the method is called.
  4. It describes a parameter that the method accepts. (correct answer)

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.

Question 19

/**

  • Checks if two Rectangle objects have the same area.
  • @param other the other Rectangle object to compare against
  • @return true if the areas are the same, false otherwise / public boolean hasSameArea(Rectangle other) { / ... */ }

Which of the following is a necessary, implicit precondition for the hasSameArea method to avoid a NullPointerException?

  1. The other parameter must not be null. (correct answer)
  2. The Rectangle other must have a positive width and height.
  3. The method must return true.
  4. This 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.

Question 20

/**

  • Calculates the factorial of a non-negative integer n (n!).
  • @param n the integer
  • @return the factorial of n */ public int factorial(int n) { // implementation computes n * (n-1) * ... * 1 }

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?

  1. Precondition: n is an integer.
  2. Precondition: The method returns a positive integer.
  3. Precondition: n >= 0. (correct answer)
  4. Precondition: The result will fit within the range of 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.