SECTION 1
Historical Context & Motivation
When programming first emerged in the 1950s and 1960s, computers had so little memory that developers wrote extremely terse, abbreviated code. Programs were short, and often only one person worked on them. As software projects grew larger in the 1970s and 1980s, teams of developers started building programs together, and a painful problem emerged: nobody could understand code written by someone else—or even their own code from a few months earlier. Code comments became the first widespread solution, allowing programmers to leave plain-English notes inside their source files.
When Sun Microsystems released Java in 1995, they introduced a groundbreaking tool called Javadoc. Javadoc let developers write specially formatted comments that could be automatically turned into polished HTML documentation—just like the official Java API pages you might have seen online. This was revolutionary because it kept documentation right next to the code, making it easier to maintain and keep accurate.
1960s • Early Code Comments
1975 • Structured Programming Movement
1995 • Java & Javadoc Released
2004 • Clean Code Movement
2020s • Modern IDE Integration
The central question this lesson addresses is: How do you write comments that are genuinely useful instead of cluttering your code with noise? The answer lies in understanding the difference between explaining what code does and explaining why it does it.
SECTION 2
Core Principles of Effective Commenting
Java supports three distinct comment styles, each serving a different purpose. Before diving into how to write great comments, you need to understand what tools are available. Single-line comments begin with // and run to the end of the line. Multi-line comments are enclosed between /* and */. Javadoc comments start with /** and end with */, and they are the key to generating professional documentation.
Comment the Why, Not the What
Use Javadoc for Public APIs
Keep Comments in Sync
Avoid Redundant Comments
// increment i above i++ adds noise, not value. Comments should provide information the code itself cannot convey.Use Tags for Structure
@param, @return, and @throws give your documentation a consistent, scannable format that tools can parse automatically.KEY TAKEAWAY
SECTION 3
Visual Explanation — The Three Comment Types
The diagram below shows the three types of Java comments side by side, illustrating their syntax, their purpose, and where they appear in a typical source file. Notice how Javadoc comments sit directly above classes, methods, and fields, while single-line and multi-line comments appear inside method bodies where they clarify implementation details.
//), multi-line (/* */), and Javadoc (/** */) comments. Notice that each example comment explains why a decision was made, not merely what the code does.In the diagram, each dashed box contains an example of a well-written comment. The single-line comment explains that binary search is used because the list is pre-sorted. The multi-line comment explains that retries happen because an external API is unreliable. These comments do not repeat the code—they provide context that would be impossible to infer from reading the code alone.
SECTION 4
How Javadoc Works — Tags and Generation
Javadoc is more than just a comment format—it is a complete documentation system. When you run the javadoc command-line tool on your source files, it reads every /** ... */ comment and transforms it into HTML pages. These pages look exactly like the official Java documentation you find at docs.oracle.com. The tool recognizes special tags that begin with the @ symbol, which provide structured information about your code.
Essential Javadoc Tags
| Tag | Where Used | What It Documents |
|---|---|---|
@param name | Methods, constructors | Describes a parameter: its meaning, valid values, and constraints |
@return | Methods | Describes the return value and what it represents |
@throws ExType | Methods | Explains when and why a specific exception is thrown |
@author | Classes, interfaces | Names the original author of the class |
@version | Classes, interfaces | Records the version number of the class |
@see | Any element | Creates a cross-reference link to related classes or methods |
{@code example} | Inline in any Javadoc | Renders text in monospace font, useful for showing code snippets |
Common Javadoc tags and their usage
Javadoc Comment Structure
Every Javadoc comment follows a consistent structure. It begins with a summary sentence—the first sentence of the comment, which the Javadoc tool extracts to appear in summary tables. After the summary, you can include a more detailed description paragraph. Finally, you add the structured tags. Here is the template:
Javadoc Template
/**
* Summary sentence describing the method's purpose.
*
* <p>Optional detailed description explaining the algorithm,
* edge cases, or design decisions behind this method.</p>
*
* @param paramName what this parameter represents
* @return what the return value means
* @throws ExceptionType when this exception occurs
*/The key principle here is that the summary sentence should describe what the method accomplishes from the caller's perspective, not the internal steps it takes. Think of it as a promise: "If you call this method with these inputs, here is what you will get back."
SECTION 5
Good Comments vs. Bad Comments
Not all comments are created equal. The difference between a helpful comment and a harmful one often comes down to whether it explains intent or just restates the obvious. The following diagram puts bad comments on the left and their improved versions on the right, so you can see the contrast clearly.
The "Delete Test"
SECTION 6
Worked Example — Documenting a Class
Let's walk through writing Javadoc for a complete class. We will document a GradeCalculator class that computes a student's weighted average grade. At each step, notice how we focus on explaining the purpose and intent rather than restating what the code does.
Documenting a GradeCalculator Class
- 1
Step 1 — Write the Class-Level Javadoc
Start with the class itself. The Javadoc should explain what the class represents and why it exists, not how it is implemented internally. Include@authorand@versiontags./** * Computes a student's final course grade using a weighted * average of assignment categories (homework, exams, projects). * * <p>Weights must sum to 1.0. This class is designed for courses * that use a standard percentage-based grading scheme.</p> * * @author Jane Doe * @version 1.0 */ - 2
Step 2 — Document the Constructor
The constructor's Javadoc should explain what state is initialized and any constraints on the parameters. Use@paramfor each parameter and@throwsif invalid input causes an exception./** * Creates a calculator with the specified category weights. * * @param weights a map of category names to their decimal * weights (e.g., "exams" → 0.40); values * must sum to 1.0 * @throws IllegalArgumentException if weights do not sum * to 1.0 (within a tolerance of 0.001) */ - 3
Step 3 — Document a Public Method
For thecalculateFinalGrademethod, describe what it calculates, what inputs it expects, what it returns, and what can go wrong. The summary sentence is a promise to the caller./** * Computes the weighted final grade across all categories. * * <p>Missing categories are treated as zero, which matches * the school's policy of penalizing incomplete work.</p> * * @param scores a map of category names to average scores * (0.0 to 100.0) for that category * @return the weighted final grade, rounded to one decimal * @throws NullPointerException if scores is null */ - 4
Step 4 — Add an Inline Implementation Comment
Inside the method body, add a single-line comment only where the logic might surprise a future reader. Here, we explain why we default missing scores to zero instead of skipping them.// Default to 0.0 for missing categories rather than // ignoring them, per school handbook Section 4.2 double score = scores.getOrDefault(category, 0.0);
KEY TAKEAWAY
SECTION 7
Strengths & Common Pitfalls
Like any tool, comments can be used well or poorly. Understanding the strengths and pitfalls of commenting helps you develop a mature sense of when and how to write them. The table below contrasts the benefits of thoughtful commenting with the most common mistakes beginners make.
| Strengths of Good Comments | Common Pitfalls |
|---|---|
| Preserve design reasoning that would otherwise be lost when the original author moves on | Over-commenting: writing a comment for every single line, creating visual clutter |
| Javadoc generates professional HTML documentation automatically, saving hours of manual work | Stale comments: changing the code but forgetting to update the comment, creating lies |
| IDEs display Javadoc as tooltips, making libraries easy to use without reading source code | Redundant comments: writing 'increments counter' above counter++, which adds no value |
| Intent comments help future developers (including yourself) make confident changes | Using comments to excuse bad code: instead of explaining confusing code, refactor it to be clear |
| Structured tags (@param, @return) enforce consistent, scannable documentation | Journal comments: keeping a change log inside source files instead of using version control |
Strengths of good commenting vs. common pitfalls
THE GOLDEN RULE
SECTION 8
Connection to Advanced Practices
As you advance in software development, you will encounter documentation practices that build on the Javadoc foundation. Understanding where Javadoc fits in the larger ecosystem helps you see it not as an isolated skill but as a stepping stone to professional software engineering.
| Concept | What You Learn Now (Javadoc) | Where It Leads (Advanced) |
|---|---|---|
| Documentation | Write Javadoc comments on classes and methods | API documentation suites, OpenAPI/Swagger specs for web services |
| Design by Contract | Use @param and @throws to describe expectations | Formal preconditions and postconditions, assertion frameworks |
| Self-Documenting Code | Name variables and methods clearly to reduce the need for comments | Clean Code principles, refactoring patterns, domain-driven design |
| Code Reviews | Comments explain decisions to reviewers | Pull request descriptions, Architecture Decision Records (ADRs) |
| Annotations | Javadoc tags add metadata to code | Java annotations (@Override, @Deprecated) encode metadata the compiler can check |
From Javadoc basics to advanced software craft
In professional teams, you will also encounter tools like Checkstyle and SonarQube that automatically flag public methods missing Javadoc. The @Deprecated annotation combined with a Javadoc @deprecated tag lets you gracefully retire old methods by explaining what to use instead. These advanced practices all trace back to the same fundamental skill you are learning now: communicating intent clearly through documentation.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
// multiply price by tax rate above the line double total = price * taxRate;. Explain why this comment is unhelpful and suggest a better one.Show answer
price * taxRate can see that multiplication is happening. A better comment would explain intent, such as: // Apply the local sales tax — rate varies by state and is loaded from config. This version tells the reader where the rate comes from and why it might change, which is information not visible in the code itself. The "delete test" confirms the original comment is noise: deleting it loses no information.Question 2: BASIC
public boolean isEligible(int age, double gpa). The method checks if a student qualifies for the honor roll (must be at least 14 years old and have a GPA of 3.5 or higher).Show answer
/**
* Determines whether a student qualifies for the honor roll.
*
* <p>Eligibility requires a minimum age of 14 and a GPA of
* at least 3.5, as defined by the school's academic policy.</p>
*
* @param age the student's age in years
* @param gpa the student's cumulative GPA on a 4.0 scale
* @return {@code true} if the student meets both criteria
*/. Notice the summary sentence describes the method's purpose, the detailed paragraph explains the business rule, and the @param and @return tags give precise descriptions. This Javadoc will appear as a helpful tooltip whenever someone hovers over the method in their IDE.Question 3: INTERMEDIATE
if (retryCount > 3) {
Thread.sleep(5000);
}
This code is not self-explanatory. Write an intent-explaining comment for it. Then explain the difference between a comment that explains 'what' versus one that explains 'why' in this context.Show answer
// After 3 failed attempts, pause 5 seconds to avoid overwhelming
// the server — it throttles clients that retry too aggressively. A 'what' comment would say something like // sleep for 5 seconds if retry count is greater than 3, which just restates the code in English. The 'why' comment reveals the design reasoning: the server throttles aggressive clients, so the pause is a deliberate strategy to stay within the server's rate limits. Without this explanation, a future developer might remove the sleep thinking it is unnecessary, causing the application to get blocked.Question 4: APPLIED
public List<Student> getTopPerformers(List<Student> students, int count). The method returns the top N students by GPA. If there are ties at the cutoff, all tied students are included, which means the returned list may be larger than count. Include appropriate Javadoc tags.Show answer
/**
* Returns the top-performing students ranked by cumulative GPA.
*
* <p>If students are tied at the cutoff position, all tied
* students are included to ensure fairness. As a result, the
* returned list may contain more than {@code count} entries.</p>
*
* @param students the full roster of students to evaluate;
* must not be null or empty
* @param count the desired number of top performers;
* must be positive
* @return an unmodifiable list of top students sorted by GPA
* descending; may exceed {@code count} due to ties
* @throws IllegalArgumentException if count is less than 1
* or if students is empty
* @see Student#getGpa()
*/. This Javadoc is excellent because the summary sentence names the purpose, the detailed paragraph explains the non-obvious tie-handling behavior, each @param describes constraints, the @return explains the sort order and possible size, and @throws documents error conditions. The @see tag cross-references the Student class.Question 5: CRITICAL THINKING
Show answer
if (user.isLoggedIn()), the code already says that—the comment is a sign that either the code is clear enough without it or (if the code is unclear) that the code should be refactored with better names. Similarly, if a method needs a paragraph of comments to explain its flow, that method is probably too long and should be broken into smaller methods with descriptive names. The balanced view is: write self-documenting code first (clear names, small methods), then add comments only where intent, context, or rationale cannot be expressed in the code itself.SUMMARY
Lesson Summary
Summary
Java provides three comment styles: single-line comments (//) for quick inline notes, multi-line comments (/* */) for longer explanations, and Javadoc comments (/** */) for generating professional HTML documentation. The most important principle is to comment the why, not the what—your comments should explain intent and reasoning that the code alone cannot convey.
Javadoc uses structured tags like @param, @return, and @throws to create a consistent, scannable contract that tells other developers how to use your code. Avoid redundant comments that restate the obvious, stale comments that contradict updated code, and over-commenting that buries valuable information in noise. Use the delete test: if deleting a comment loses no information, it should not exist.