Opening subject page...
Loading your content
Writing clear, purposeful comments that make code readable, maintainable, and exam-ready.
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.
/* block comment */ syntax, allowing multi-line annotations anywhere in the source. This convention heavily influences Java's comment syntax./** ... */). The Javadoc tool generates HTML API documentation directly from source code.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.
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.
// 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/* 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./** and ends with */. Parsed by the Javadoc tool to produce HTML API docs. Supports tags like @param, @return, and @throws.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.
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).
| 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 |
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.
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.
| 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. |
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.
@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
*/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)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;
}@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.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 |
@param and @return tags. State preconditions explicitly.i++, don't write // increment i.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 |
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.
// add 1 to count
count++;
Which of the following best explains why this comment is considered poor practice?String parameter name and returns an int?/**
* 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?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./**
* @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.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.