Home

Tutoring

Subjects

Live Classes

Study Coach

Essay Review

On-Demand Courses

Colleges

Games


Sign up

Log in

Opening subject page...

Loading your content

  1. AP Computer Science a
  2. Documentation with Comments

// This method returns.../** @param name *//* block comment */// precondition:/** postcondition */
AP COMPUTER SCIENCE A • USING OBJECTS AND METHODS

Documentation with Comments

Writing clear, purposeful comments that make code readable, maintainable, and exam-ready.

SECTION 1

Historical Context & Motivation

From the earliest days of computing, programmers recognized that source code alone is insufficient for conveying the intent behind a solution. Machine instructions execute without ambiguity, but the reasoning that led a developer to choose a particular algorithm, data structure, or design pattern is invisible to anyone reading raw code months—or years—later. Documentation with comments arose as the primary in-source mechanism for bridging this gap between what a program does and why it does it.

Early programming languages such as FORTRAN (1957) included minimal annotation facilities—usually a single character in column one of a punch card. As software projects grew from hundreds of lines written by a single person to millions of lines maintained by distributed teams, the need for structured, standardized documentation became critical. Languages evolved richer commenting syntax, and entire documentation-generation ecosystems emerged to extract structured metadata from source files.

1957
FORTRAN Comment Lines
FORTRAN introduces the 'C' character in column 1 to mark an entire line as a comment, establishing the convention that compilers should ignore human-readable annotations.
1972
C Language Comments
The C programming language formalizes /* block comment */ syntax, allowing multi-line annotations anywhere in the source. This convention heavily influences Java's comment syntax.
1995
Java & Javadoc Launch
Sun Microsystems releases Java 1.0 with built-in support for three comment styles—single-line, multi-line, and Javadoc (/** ... */). The Javadoc tool generates HTML API documentation directly from source code.
2003
AP Computer Science Adopts Java
The College Board transitions the AP Computer Science A exam from C++ to Java, making Javadoc-style comments and precondition/postcondition documentation a standard part of the AP curriculum.
2020s
Modern Documentation Culture
Contemporary development emphasizes self-documenting code complemented by strategic comments. Tools like IDE pop-ups render Javadoc inline, making well-commented APIs instantly accessible to every developer on a team.

The central question this lesson addresses is straightforward yet deceptively deep: How do you write comments that genuinely improve code comprehension rather than merely parroting what the code already says? On the AP Computer Science A exam, you will encounter Javadoc-style comments in the Quick Reference, read them to understand unfamiliar classes and methods, and write comments in your free-response answers that demonstrate clear thinking. Mastering this skill is essential to both real-world development and exam success.

SECTION 2

Core Principles & Definitions

Java supports three distinct comment syntaxes, each serving a specific purpose in the documentation ecosystem. Understanding when and why to use each type is foundational to writing professional-quality code. A comment is any text that the Java compiler ignores entirely—it has zero effect on the compiled bytecode. Comments exist solely for human readers: your future self, your teammates, your teacher, and the AP exam graders.

1

Single-Line Comment (//)

Everything after // on a line is ignored by the compiler. Best for brief inline explanations of tricky logic or variable purpose. Example: int count = 0; // tracks valid entries
2

Multi-Line Comment (/* */)

Spans from /* to */ and may cover any number of lines. Useful for temporarily disabling blocks of code during debugging or for longer explanations that exceed a single line.
3

Javadoc Comment (/** */)

Begins with /** and ends with */. Parsed by the Javadoc tool to produce HTML API docs. Supports tags like @param, @return, and @throws.
4

Preconditions & Postconditions

A precondition states what must be true before a method is called. A postcondition states what will be true after the method finishes. Both appear frequently on the AP exam's Quick Reference.
5

Self-Documenting Code

Well-chosen variable names, method names, and class structure reduce the need for comments. Comments should explain why something is done, not what is done—the code itself should convey the 'what.'
✦ KEY TAKEAWAY
Think of comments the way an architect thinks of annotations on a blueprint. The blueprint itself shows where each wall and beam goes—that is analogous to your code. But the architect's handwritten notes explain why a load-bearing wall was placed in a particular location, or what building codes demanded a specific material. Without those annotations, a future contractor would have to reverse-engineer the reasoning. Good comments capture the reasoning the code cannot express on its own.
SECTION 3

Visual Explanation — Comment Anatomy

The diagram below illustrates the three Java comment types applied to a simple method. Each comment type is color-coded so you can see its scope and placement relative to the executable code. Notice how the Javadoc comment sits immediately before the method header, the multi-line comment encloses a block of explanation, and the single-line comments annotate specific lines.

Three Comment Types in a Java Method/** Javadoc Comment *//** * Calculates the area of a rectangle. * @param width the width (precondition: width > 0) * @param height the height (precondition: height > 0)JAVADOCpublic double getArea(double width, double height) {/* Multi-line Comment */ /* We multiply rather than calling Math.pow to keep it simple. */BLOCK double area = width * height; // postcondition: area >= 0SINGLE return area;}LegendJavadoc /** ... */ — API documentationBlock /* ... */ — internal notesSingle // — inlineThe compiler ignores all three comment types. Only executable code produces bytecode.Colors correspond to comment scope indicators on the left border.
Each comment type is highlighted with a colored left border: pink for Javadoc, violet for block comments, and cyan for single-line comments. Notice how the Javadoc comment precedes the method header, providing the public interface documentation that tools can extract automatically.

Observe that the Javadoc comment includes @param tags that name each parameter and state the precondition in parentheses. This is the pattern you will see repeatedly in the AP exam's Quick Reference. When the exam introduces a class you have never seen—such as GridWorld's Actor class—you rely on exactly this style of documentation to determine what each method expects as input, what it returns, and what assumptions (preconditions) it makes.

SECTION 4

How Comments Work — Compiler Behavior & Javadoc Tags

During compilation, the Java compiler's lexical analyzer (the first phase of compilation) strips all comments from the token stream before syntactic analysis begins. This means comments carry absolutely no runtime cost: they do not increase the size of the .class file, they do not slow execution, and they cannot introduce bugs. The compiler treats // as a signal to discard all remaining characters on that line, /* as a signal to discard everything until the matching */, and /** identically to /* (though the Javadoc tool processes these separately).

Essential Javadoc Tags for AP CSA

Javadoc tags relevant to AP Computer Science A
TagSyntaxPurposeAP Exam Relevance
@param@param name descriptionDocuments a method parameter and its expected valuesAppears in Quick Reference for every method; encodes preconditions
@return@return descriptionDescribes what the method returnsCritical for understanding method output; encodes postconditions
@throws@throws ExceptionType when...Lists exceptions the method may throwLess common on AP exam but reinforces robustness
PreconditionFree-form text, often after @paramStates what must be true before the method is invokedHeavily tested—FRQs often state preconditions you must honor
PostconditionFree-form text, often after @returnStates what is guaranteed to be true after the method completesDefines the 'contract' your code must fulfill in FRQs
⚠️ Preconditions Are Not Checked by the Compiler
A precondition is a promise from the caller to the method. If the caller violates a precondition (e.g., passing a negative value when the precondition requires a positive integer), the method's behavior is undefined. On the AP exam, you may assume preconditions are met—you do not need to add defensive checks unless the problem explicitly asks you to.

The relationship between preconditions and postconditions forms a method contract: if the caller satisfies the preconditions, the method guarantees the postconditions. This design-by-contract philosophy, articulated by Bertrand Meyer in the late 1980s, underpins how the AP exam presents method specifications. When you read a method header in the Quick Reference, you are reading one side of this contract—and your free-response code must fulfill the other side.

SECTION 5

Detailed Breakdown — When to Use Each Comment Style

Choosing the right comment style is not merely a matter of syntax—it signals to readers (and to graders) what kind of information you are conveying. The diagram below maps each comment type to its ideal use cases, creating a decision framework you can internalize for both production code and exam responses.

Comment Decision FlowchartNeed to add a comment?Is it part of the public API?YESNOUse Javadoc /** ... */@param, @return, pre/postMore than one line needed?YESNOUse Block /* ... */Design rationale, algorithm notesUse //Quick inline noteGolden Rule: Comment the WHY, not the WHATBad: // increment x by 1 → x++; Good: // advance to next student index → x++;
This flowchart guides your choice of comment type. Start with the question 'Is this part of the public API?' If yes, use Javadoc. If not, decide between block comments for multi-line explanations and single-line comments for brief inline notes.

Good Comments vs. Bad Comments

Comment quality comparison
QualityExampleWhy It's Good / Bad
GOOD// use insertion sort because n < 20 on averageExplains the reasoning behind an algorithm choice—something the code cannot express.
BAD// set x to 5 above x = 5;Restates what the code already says. Adds no information.
GOOD// precondition: list is sorted in ascending orderDocuments a requirement that callers must satisfy—critical for binary search correctness.
BAD// TODO: fix this laterVague, non-actionable, and would lose points on the AP exam if left without resolution.
GOOD/** @return the number of elements that match target, or 0 if none found */Postcondition is clearly stated, covering both the normal case and the edge case.
SECTION 6

Worked Example — Documenting a Method from Scratch

Suppose you are given the following AP-style prompt: "Write a method isInRange that takes three int parameters—value, low, and high—and returns true if value is between low and high inclusive. Precondition: low <= high." Let us walk through writing fully documented code.

Documenting isInRange

Step 1 — Write the Javadoc Comment

Begin with a Javadoc comment immediately before the method header. Start with a one-sentence summary of the method's purpose, then use @param for each parameter, including the precondition, and @return for the return value.
/** Determines whether value lies within the range [low, high]. * @param value the number to test * @param low the lower bound (precondition: low <= high) * @param high the upper bound * @return true if low <= value <= high; false otherwise */

Step 2 — Write the Method Header

The method returns a boolean and is public static since it does not depend on instance state. The parameter names match the Javadoc tags exactly.
public static boolean isInRange(int value, int low, int high)

Step 3 — Implement the Body with an Inline Comment

The logic is a single boolean expression. Because the precondition guarantees low <= high, we only need to check that value falls between them. An inline comment clarifies why we trust this ordering.
{ // No need to check low <= high (guaranteed by precondition) return value >= low && value <= high; }

Step 4 — Review Against the Contract

Verify that the Javadoc's postcondition (@return) matches the actual return expression. If value is 5, low is 1, and high is 10, the expression evaluates to true—consistent with [1, 10]. If value is 0, the result is false. The contract holds.
Documentation is consistent with implementation ✓
SECTION 7

Strengths, Limitations & Best Practices

Comments are powerful when used judiciously, but they are not without pitfalls. Over-commenting clutters code and can become a maintenance burden—comments that fall out of sync with the code they describe are worse than no comments at all, because they actively mislead the reader. The table below summarizes the key tradeoffs.

Strengths vs. Limitations of code comments
StrengthsLimitations
Capture intent and rationale that code syntax cannot expressStale comments (out of sync with code) introduce confusion and errors
Javadoc generates browsable API documentation automaticallyExcessive or trivial comments reduce signal-to-noise ratio
Precondition/postcondition contracts clarify method responsibilitiesComments cannot be compiled or type-checked—they may contain errors
Zero runtime overhead—compiler strips them completelyOver-reliance on comments can mask poorly named variables and methods
Essential for AP exam Quick Reference and FRQ grading clarityOn timed exams, lengthy comments may waste time if not asked for
💡 BEST PRACTICE
Think of your code as a well-written research paper. The code itself is the data and analysis—it should be clear enough that a knowledgeable reader can follow the logic. Comments are your footnotes: they provide context, cite design decisions, and flag assumptions that are not obvious from the primary text. A paper drowning in footnotes is as hard to read as one with none at all. Aim for strategic, high-value annotations that complement self-documenting code.
  • Write Javadoc for every public method. Include @param and @return tags. State preconditions explicitly.
  • Use single-line comments for 'why,' not 'what.' If the code says i++, don't write // increment i.
  • Update comments when you change code. A stale comment is worse than no comment.
  • On the AP exam, add brief comments to clarify non-obvious FRQ logic. Graders appreciate intent signals, but do not over-comment at the cost of coding time.
SECTION 8

Connection to Professional & Advanced Practices

The commenting conventions you learn for AP CSA are a subset of a much larger discipline known as software documentation engineering. In industry, teams use Javadoc-style annotations as the foundation for automatically generated API references—Oracle's entire Java SE documentation is produced this way. Beyond Javadoc, professional developers employ documentation tools like Swagger for RESTful APIs, Doxygen for C/C++ projects, and Sphinx for Python. The underlying philosophy—comment the contract, not the implementation—scales from a 20-line AP free response to a million-line enterprise system.

AP CSA comments vs. professional documentation practices
AP CSA LevelProfessional / Advanced Level
Single-line comments (//) for inline notesLinting rules enforce comment density and style (e.g., Checkstyle, ESLint)
Javadoc with @param and @returnFull Javadoc with @throws, @see, @since, @deprecated, custom tags
Preconditions stated informally in commentsFormal contracts enforced via assertions, annotations (@NonNull), or design-by-contract frameworks
Reading Quick Reference documentationNavigating large-scale generated API docs (e.g., docs.oracle.com)
Manual review for comment qualityAutomated CI/CD pipelines that reject code without documentation coverage

If you continue into software engineering, you will encounter the concept of API-first design, where the documentation (i.e., the contract) is written before the implementation. This practice, which echoes test-driven development, ensures that the public interface is well-thought-out and that clients know exactly what to expect. The AP exam's habit of providing a method header with comments and asking you to implement the body is, in effect, an exercise in API-first design—you are fulfilling a contract that has already been defined.

SECTION 9

Practice Problems

PROBLEM 1 — CONCEPTUAL
Consider the following comment: // add 1 to count count++; Which of the following best explains why this comment is considered poor practice?
PROBLEM 2 — BASIC
Which of the following correctly uses Javadoc syntax to document a method that takes a String parameter name and returns an int?
PROBLEM 3 — INTERMEDIATE
A method has the following Javadoc: /** * Returns the index of the first occurrence of target in arr. * @param arr the array to search (precondition: arr is not null) * @param target the value to find * @return the index of target, or -1 if target is not in arr */ Based on this documentation, which of the following is a valid postcondition of the method?
PROBLEM 4 — APPLIED
Write a complete Javadoc comment and method header for a method called averagePositives that accepts an array of double values and returns the average of all positive values in the array. If no positive values exist, it returns 0.0. The precondition is that the array is not null and has at least one element. Include appropriate @param and @return tags, and clearly state the precondition and postcondition.
PROBLEM 5 — CRITICAL THINKING
A student writes the following method with comments: /** * @param list the list * @return the list sorted */ public ArrayList<Integer> process(ArrayList<Integer> list) { // sort the list Collections.sort(list); // remove duplicates for (int i = list.size() - 1; i > 0; i--) { if (list.get(i).equals(list.get(i - 1))) list.remove(i); } return list; } Identify at least three specific documentation problems in this code, and rewrite the Javadoc comment and any necessary inline comments so that they accurately and completely describe the method's behavior. Explain why each change improves the documentation.
SUMMARY

Summary — Documentation with Comments

Java provides three comment styles: single-line comments (//) for brief inline annotations, block comments (/* */) for multi-line internal notes, and Javadoc comments (/** */) for generating API documentation. All three are stripped by the compiler during lexical analysis and carry zero runtime cost. The key Javadoc tags for AP CSA are @param (to describe parameters and state preconditions) and @return (to describe the return value and state postconditions). Together, preconditions and postconditions form a method contract that defines the mutual obligations of caller and method.

Effective comments explain why code is written a certain way, not what the code does—the code itself should convey the 'what' through self-documenting naming. On the AP exam, you read Javadoc-style documentation in the Quick Reference to understand unfamiliar classes and methods, and you demonstrate clear intent in free-response answers through strategic commenting. Remember: stale comments that no longer match the code are worse than no comments at all—keep your documentation accurate and concise.

Varsity Tutors • AP Computer Science A • Documentation with Comments