AP Computer Science A — Unit 1

1.8 Documentation with Comments

How, when, and why to document Java programs using single-line, multi-line, and Javadoc comments.

Overview

In AP CSA, documentation is the written explanation of what your code does and why you wrote it that way. Clear, accurate comments make your program easier to read, debug, maintain, and share. On teams, good comments are as important as good variable names.

Exam note: Comments don’t change how code runs or how it’s graded for correctness, but they showcase your understanding and make logic easier to follow.

Types of Comments in Java

1) Single-Line //

Use for short notes that clarify a line or two.

// Calculate the area of a circle
double area = Math.PI * radius * radius;

2) Multi-Line /* ... */

Use when you need to explain a whole block or summarize an algorithm.

/*
Reads input scores, computes the average,
and prints a rounded result.
*/

3) Javadoc /** ... */

Use above classes and methods to generate API docs with Javadoc. Include @param and @return tags.

/**
 * Calculates the area of a circle.
 * @param radius the circle's radius
 * @return the computed area
 */
public static double calculateArea(double radius) {
    return Math.PI * radius * radius;
}

Why Documentation Matters

  1. Clarity: Explains intent behind code decisions.
  2. Debugging: Speeds up finding and fixing logic errors.
  3. Maintenance: Future changes are safer and faster.
  4. Collaboration: Teammates can understand and extend your work.
  5. Professionalism: Mirrors industry standards and habits.

Best Practices

  • Comment the “why,” not the obvious “what.”
    // add 1 to x
    // Adjust for zero-based index
  • Keep comments current. Out-of-date comments are worse than none.
  • Use a consistent style. Place comments where eyes naturally go.
  • Prefer descriptive names. Good identifiers reduce the need for comments.
  • Document public methods with Javadoc. Include purpose, parameters, return value, and edge cases.

Well-Documented Example

/**
 * Program: CircleAreaCalculator
 * Author: Your Name
 * Purpose: Reads a radius and prints the circle's area.
 */
public class CircleAreaCalculator {

    /**
     * Entry point: computes the area using A = πr².
     * Assumes radius is non-negative.
     * @param args unused
     */
    public static void main(String[] args) {
        double radius = 5.0;           // example user-provided radius
        double area = Math.PI * radius * radius; // formula for area
        System.out.println("Area: " + area);     // display result
    }
}

Quick Checklist

  • Does every public method have a clear Javadoc block?
  • Do comments explain why tricky code is needed?
  • Are comments up to date with the current logic?
  • Are names (classes, methods, variables) descriptive?
  • Could a teammate understand this without asking you questions?
```