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
1972 • C Language Comments
/* block comment */ syntax, allowing multi-line annotations anywhere in the source. This convention heavily influences Java's comment syntax.1995 • Java & Javadoc Launch
/** ... */). The Javadoc tool generates HTML API documentation directly from source code.2003 • AP Computer Science Adopts Java
2020s • Modern Documentation Culture
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.
Single-Line Comment (//)
// 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 entriesMulti-Line Comment (/* */)
/* 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.Javadoc Comment (/** */)
/** and ends with */. Parsed by the Javadoc tool to produce HTML API docs. Supports tags like @param, @return, and @throws.Preconditions & Postconditions
Self-Documenting Code
KEY TAKEAWAY
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.
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
| Tag | Syntax | Purpose | AP Exam Relevance |
|---|---|---|---|
@param | @param name description | Documents a method parameter and its expected values | Appears in Quick Reference for every method; encodes preconditions |
@return | @return description | Describes what the method returns | Critical for understanding method output; encodes postconditions |
@throws | @throws ExceptionType when... | Lists exceptions the method may throw | Less common on AP exam but reinforces robustness |
| Precondition | Free-form text, often after @param | States what must be true before the method is invoked | Heavily tested—FRQs often state preconditions you must honor |
| Postcondition | Free-form text, often after @return | States what is guaranteed to be true after the method completes | Defines the 'contract' your code must fulfill in FRQs |
Javadoc tags relevant to AP Computer Science A
Preconditions Are Not Checked by the Compiler
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.
Good Comments vs. Bad Comments
| Quality | Example | Why It's Good / Bad |
|---|---|---|
| GOOD | // use insertion sort because n < 20 on average | Explains 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 order | Documents a requirement that callers must satisfy—critical for binary search correctness. |
| BAD | // TODO: fix this later | Vague, 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. |
Comment quality comparison
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
- 1
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@paramfor each parameter, including the precondition, and@returnfor 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 */ - 2
Step 2 — Write the Method Header
The method returns abooleanand ispublic staticsince 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) - 3
Step 3 — Implement the Body with an Inline Comment
The logic is a single boolean expression. Because the precondition guaranteeslow <= high, we only need to check thatvaluefalls 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; } - 4
Step 4 — Review Against the Contract
Verify that the Javadoc's postcondition (@return) matches the actual return expression. Ifvalueis 5,lowis 1, andhighis 10, the expression evaluates totrue—consistent with [1, 10]. Ifvalueis 0, the result isfalse. 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 | Limitations |
|---|---|
| Capture intent and rationale that code syntax cannot express | Stale comments (out of sync with code) introduce confusion and errors |
| Javadoc generates browsable API documentation automatically | Excessive or trivial comments reduce signal-to-noise ratio |
| Precondition/postcondition contracts clarify method responsibilities | Comments cannot be compiled or type-checked—they may contain errors |
| Zero runtime overhead—compiler strips them completely | Over-reliance on comments can mask poorly named variables and methods |
| Essential for AP exam Quick Reference and FRQ grading clarity | On timed exams, lengthy comments may waste time if not asked for |
Strengths vs. Limitations of code comments
BEST PRACTICE
- ✓ Write Javadoc for every public method. Include
@paramand@returntags. 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 Level | Professional / Advanced Level |
|---|---|
Single-line comments (//) for inline notes | Linting rules enforce comment density and style (e.g., Checkstyle, ESLint) |
Javadoc with @param and @return | Full Javadoc with @throws, @see, @since, @deprecated, custom tags |
| Preconditions stated informally in comments | Formal contracts enforced via assertions, annotations (@NonNull), or design-by-contract frameworks |
| Reading Quick Reference documentation | Navigating large-scale generated API docs (e.g., docs.oracle.com) |
| Manual review for comment quality | Automated CI/CD pipelines that reject code without documentation coverage |
AP CSA comments vs. professional documentation practices
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
Question 1: CONCEPTUAL
// add 1 to count
count++;
Which of the following best explains why this comment is considered poor practice?- A. The comment uses single-line syntax when a block comment is required.
- B. The comment merely restates what the code does, providing no additional insight into why the increment occurs.
- C. The comment is placed on the wrong line; it should appear after the statement.
- D. The comment will cause a compilation error because it does not use Javadoc syntax.
Show answer (B)
count++ already communicates that count is incremented; the comment adds no value. A better comment would explain the reason for the increment, such as // found a valid entry, so update the running total. Option A is wrong because there is no rule requiring block comments here. Option C is wrong because the placement (above the code) is standard convention. Option D is wrong because single-line comments are syntactically valid and never cause compilation errors.Question 2: BASIC
String parameter name and returns an int?- A.
/* @param name the student's name @return the student's ID */ - B.
/** @param name the student's name * @return the student's ID */ - C.
// @param name the student's name // @return the student's ID - D.
/** @parameter name the student's name * @returns the student's ID */
Show answer (B)
/** (not /*) and use the standard tags @param and @return. Option A uses /* instead of /**, so the Javadoc tool would not parse it. Option C uses single-line comment syntax, which the Javadoc tool ignores entirely. Option D invents non-existent tags @parameter and @returns—the correct tags are @param and @return (no 's').Question 3: INTERMEDIATE
/**
* 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?- A. The returned value is always greater than or equal to 0.
- B. If the returned value is not −1, then
arr[returnValue] == target. - C. The method modifies
arrby removing target from it. - D. The method throws an exception if
arris null.
Show answer (B)
@return tag states that the method returns the index of target or −1 if absent. Therefore, when the return value is not −1, accessing arr at that index must yield target—this is the implicit postcondition. Option A is wrong because the method can return −1, which is less than 0. Option C is wrong because nothing in the documentation suggests mutation of the array. Option D is wrong because the precondition states that arr is not null—since the caller is responsible for meeting preconditions, the method need not handle a null array.Question 4: APPLIED
5 ptsaveragePositives 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.Show answer
/** and includes a one-sentence description of the method's purpose (e.g., 'Computes the average of all positive values in the given array').
Point 2 — @param tag with precondition: Uses @param values (or equivalent name) with a description that explicitly states the precondition: array is not null and has length ≥ 1.
Point 3 — @return tag with postcondition: Uses @return that describes both the normal case (average of positive values) and the edge case (returns 0.0 if no positive values exist).
Point 4 — Correct method header: Method returns double, accepts double[] as a parameter, and uses a meaningful method name (averagePositives). Access modifier is public or public static.
Point 5 — Javadoc closing and formatting: Comment ends with */ and is placed directly before the method header. Tags are properly formatted with asterisk leaders.
Sample answer:
/**
* Computes the average of all positive values in the given array.
* @param values the array of doubles to examine
* (precondition: values is not null and values.length >= 1)
* @return the average of all elements > 0.0, or 0.0 if no positive elements exist
*/
public static double averagePositives(double[] values)Question 5: CRITICAL THINKING
3 pts/**
* @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.Show answer
@return says 'the list sorted' but the method also removes duplicates; the postcondition is incomplete and misleading. (c) The @param description is vague ('the list') and omits the precondition (e.g., list is not null). (d) The method name process is non-descriptive. (e) The inline comments restate 'what' rather than 'why.' (f) The Javadoc does not mention that the method mutates the input list.
Point 2 — Provides corrected Javadoc: A rewritten Javadoc should include a clear summary sentence, a @param with the precondition, and a @return that describes the complete postcondition (sorted, duplicate-free, same reference). Example:
/**
* Sorts the given list and removes duplicate values.
* @param list the list of integers to process
* (precondition: list is not null)
* @return the same list, sorted in ascending order with all duplicates removed
*/
Point 3 — Explains improvements: The student explains that the corrected Javadoc (a) adds a summary so readers know the method's purpose at a glance, (b) makes the postcondition accurate and complete, (c) states that the method mutates the original list (important for callers to know), and (d) the inline comments should be replaced with 'why' explanations (e.g., '// iterate backward so that removals do not shift unprocessed elements').SUMMARY
Summary — Documentation with Comments
Summary
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.