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.
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.
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.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.
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 |
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:
/**
* 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."
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.
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.
@author and @version tags./**
* 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
*/@param for each parameter and @throws if 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)
*/calculateFinalGrade method, 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
*/// Default to 0.0 for missing categories rather than
// ignoring them, per school handbook Section 4.2
double score = scores.getOrDefault(category, 0.0);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 |
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 |
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.
Practice Problems
// multiply price by tax rate above the line double total = price * taxRate;. Explain why this comment is unhelpful and suggest a better one.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).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.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.Lesson 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.