PrepGo

Documentation with Comments - AP Computer Science A Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 9 minutes to read.

Getting Started

In programming, code is read by humans far more often than it is written. To make programs understandable, maintainable, and easier to debug, developers must communicate their intent not just to the computer, but to other people (and their future selves). Documentation with comments is the primary way programmers embed human-readable explanations and logic directly within their source code.

What You Should Be Able to Do

  • Explain the purpose of comments in a Java program.

  • Use single-line and multi-line comments to document code.

  • Define and identify preconditions for a method.

  • Define and identify postconditions for a method.

  • Describe how documentation improves program readability and maintainability.

Key Concepts & Java Implementation

The Core Idea

A comment is a note written in the source code for a human reader. The Java compiler completely ignores comments; they have no effect on how the program runs. Their sole purpose is to improve the clarity and readability of the code.

Programmers use comments to:

  1. Explain Purpose: Describe what a class, method, or complex block of code is designed to do.

  2. Clarify Logic: Explain a non-obvious or intricate part of an algorithm.

  3. State Assumptions: Document any assumptions made about the data or the program's state.

Writing good comments is a critical skill for software development, especially when working in teams. Clear documentation allows other developers to understand, use, and modify your code without having to decipher every line from scratch.

Syntax & Implementation

Java provides two primary ways to write comments.

Syntax Table

SyntaxTypePurpose & Use Case
// textSingle-Line CommentComments out all text from the // to the end of the line. Ideal for brief, inline notes.
/* text */Multi-Line CommentComments out all text between /* and */, even across multiple lines. Used for longer explanations or for documenting methods.

Annotated Java Examples

  1. Single-Line Comments are perfect for explaining the purpose of a single variable or a simple line of code.

    
    // The Player class stores information about a user in the game.
    
    public class Player {
    
        private int score; // Stores the player's current score.
    
        private int level; // Represents the player's current level.
    
    
        public void increaseScore(int points) {
    
            this.score = this.score + points; // Add points to the existing score.
    
        }
    
    }
    
  2. Multi-Line Comments are useful for providing a more detailed overview of a method or a complex section of code.

    
    public class Calculator {
    
        /*
    
         This method calculates the final price of an item
    
         after applying a discount and adding sales tax.
    
         It ensures the final price is never negative.
    
        */
    
        public double calculateFinalPrice(double initialPrice, double discountPercent) {
    
            double discountedPrice = initialPrice * (1.0 - discountPercent);
    
            double finalPrice = discountedPrice * 1.08; // Apply 8% sales tax.
    
            return finalPrice;
    
        }
    
    }
    

Preconditions and Postconditions

For methods, a structured form of documentation is often used to describe their "contract"—what they expect and what they guarantee.

A precondition is a condition that must be true before a method is called. If the preconditions are not met, the method is not guaranteed to work correctly. They often describe constraints on the parameters.

A postcondition is a condition that is guaranteed to be true after a method has finished executing, assuming all preconditions were met. They often describe the return value or changes to the object's state.

Annotated Java Example

This example shows how to document a method's contract using a multi-line comment.


public class GradeAnalyzer {


    /**

     * Calculates the average of an array of test scores.

     *

     * Precondition: The input array `scores` is not null and contains

     *               at least one element. All elements are >= 0.

     * Postcondition: Returns the arithmetic mean of the elements in `scores`.

     *                The original `scores` array is not modified.

     */

    public double calculateAverage(int[] scores) {

        double sum = 0;

        for (int score : scores) {

            sum = sum + score;

        }

        return sum / scores.length;

    }

}

Analysis

In the calculateAverage method:

  • The precondition warns the caller that they must provide a valid array (scores is not null, has at least one element). If a caller passes an empty array, the code would crash with an ArithmeticException (division by zero). The precondition makes the caller responsible for providing valid input.

  • The postcondition promises what the method will deliver: the correct average value. It also guarantees that the method does not have side effects on the input array (it is "not modified").

Java Syntax Quick-Reference

A compact list of the comment syntax introduced in this topic.

  • // comment text: Marks the rest of the line as a single-line comment, which is ignored by the compiler.

  • /* comment text */: Marks everything between the opening /* and closing */ as a multi-line (or block) comment.

Core Code Examples & Terminology

  • Comment: A textual note embedded in source code for human readers. Comments are ignored by the compiler and do not affect the program's execution.

  • Precondition: A condition that must be true before a method is invoked for it to function correctly. It defines the method's expectations for its parameters and the object's state.

  • Postcondition: A condition that is guaranteed to be true after a method has completed its execution, provided that its preconditions were met. It describes the method's outcome, such as its return value.

  • Core Snippet 1: Inline Comment

    
    final int MAX_ATTEMPTS = 3; // A constant for the number of login retries.
    

    This shows a single-line comment used to clarify the purpose of a variable.

  • Core Snippet 2: Method Documentation

    
    /*
    
     * Precondition: `divisor` is not zero.
    
     * Postcondition: Returns the result of `numerator` divided by `divisor`.
    
     */
    
    public double divide(double numerator, double divisor) {
    
        return numerator / divisor;
    
    }
    

    This demonstrates the standard practice of using a multi-line comment to document a method's contract.

Core Skill Check

  • Code Tracing: What is the purpose of the comment in this line of code: boolean isLoggedIn = false; // Tracks the user's session status.?

    • Answer: To explain the meaning and purpose of the isLoggedIn variable.
  • Debugging: This code has a logical error. How would you fix the code to match the comment?

    
    // Calculates the area of a rectangle.
    
    int area = length + width;
    
    • Answer: int area = length * width;
  • Application: Write a single-line comment for the following line of code to explain that it sets a default value.

    
    String username = "guest";
    
    • Answer: String username = "guest"; // Sets a default username.

Common Misconceptions & Errors

  • Comments can fix broken code.

    • Correction: Comments are completely ignored by the compiler. They cannot change program logic or fix errors. They can only help a human developer understand the code in order to fix it.
  • More comments are always better.

    • Correction: Comments should add value by explaining the why, not the what. A comment like x++; // Increment x by one is redundant and adds clutter. Good comments clarify complex or non-obvious code.
  • Forgetting to close a multi-line comment.

    • Correction: If you write /* without a matching */, the compiler will treat all subsequent code as part of the comment, leading to confusing syntax errors.
  • Letting comments become outdated.

    • Correction: If you change the logic of your code, you must also update its corresponding comments. An incorrect comment can be more misleading than no comment at all.

Summary

Documentation is an essential practice in software development that makes code understandable, maintainable, and collaborative. Java provides two primary mechanisms for this: single-line comments (//) for brief notes and multi-line comments (/* ... */) for longer explanations. A key use of documentation is to define a method's "contract" through preconditions and postconditions. Preconditions state what must be true before a method is called, while postconditions describe what will be true after it completes. Writing clear, concise, and accurate comments is as important as writing correct code.