JAVA • SOFTWARE CRAFT AND COMMUNICATION

Javadoc & Comments — Write Javadoc and comments that explain intent

Learn to write comments that explain why your code exists, not just what it does.

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
Assembly and FORTRAN introduced the concept of source-code comments. These were simple notes ignored by the compiler, helping programmers remember what sections of code were supposed to do.
1975
Structured Programming Movement
As teams grew, pioneers like Donald Knuth championed 'literate programming,' arguing that source code should be readable like prose. Comments shifted from optional afterthoughts to essential practice.
1995
Java & Javadoc Released
Sun Microsystems shipped Java 1.0 with the Javadoc tool built in. For the first time, developers could generate professional API documentation directly from source-code comments using special tags like @param and @return.
2004
Clean Code Movement
Robert C. Martin and others popularized the idea that comments should explain intent—the 'why'—rather than repeat what the code already says. This shifted how the industry thought about commenting.
2020s
Modern IDE Integration
Today's IDEs like IntelliJ and VS Code render Javadoc in real-time tooltips, making well-documented code instantly understandable. AI coding assistants also rely on Javadoc to give better suggestions.

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.

1

Comment the Why, Not the What

Good code should be clear enough that a reader can see what it does. Your comments should explain why a decision was made—the intent behind the code.
2

Use Javadoc for Public APIs

Every public class, method, and field should have a Javadoc comment. This becomes the contract that tells other developers how to use your code without reading every line.
3

Keep Comments in Sync

A comment that contradicts the code is worse than no comment at all. When you update code, always update the related comments at the same time.
4

Avoid Redundant Comments

Writing // increment i above i++ adds noise, not value. Comments should provide information the code itself cannot convey.
5

Use Tags for Structure

Javadoc tags like @param, @return, and @throws give your documentation a consistent, scannable format that tools can parse automatically.
✦ KEY TAKEAWAY
Think of comments like sticky notes on a recipe. You would not write "add salt" on a sticky note—that is already in the recipe itself. But you might write "Grandma always added extra salt here because our oven runs cool." That note explains intent—the reasoning behind the choice—and that is what makes a comment truly valuable.

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.

The three columns show single-line (//), 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

Common Javadoc tags and their usage
TagWhere UsedWhat It Documents
@param nameMethods, constructorsDescribes a parameter: its meaning, valid values, and constraints
@returnMethodsDescribes the return value and what it represents
@throws ExTypeMethodsExplains when and why a specific exception is thrown
@authorClasses, interfacesNames the original author of the class
@versionClasses, interfacesRecords the version number of the class
@seeAny elementCreates a cross-reference link to related classes or methods
{@code example}Inline in any JavadocRenders 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:

📝 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."

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.

Four pairs of bad (left, red) and good (right, green) comments. In every case, the good comment adds information that cannot be derived from reading the code alone.
🗑️ The "Delete Test"
Here is a quick way to test if a comment is worth keeping: imagine deleting it. If you lose information that you cannot recover by reading the code, the comment is valuable. If the code already tells you the same thing, the comment is just noise—delete it.

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 JavadocStart with the class itself. The Javadoc should explain what the class represents and why it exists, not how it is implemented internally. Include @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 */
2
Step 2 — Document the ConstructorThe constructor's Javadoc should explain what state is initialized and any constraints on the parameters. Use @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) */
3
Step 3 — Document a Public MethodFor the 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 */
4
Step 4 — Add an Inline Implementation CommentInside 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
Notice the pattern: the Javadoc comments describe the contract (what the caller can expect), while the inline comment inside the method explains a non-obvious design decision. Together, they form a complete picture of intent.

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 commenting vs. common pitfalls
Strengths of Good CommentsCommon Pitfalls
Preserve design reasoning that would otherwise be lost when the original author moves onOver-commenting: writing a comment for every single line, creating visual clutter
Javadoc generates professional HTML documentation automatically, saving hours of manual workStale 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 codeRedundant comments: writing 'increments counter' above counter++, which adds no value
Intent comments help future developers (including yourself) make confident changesUsing comments to excuse bad code: instead of explaining confusing code, refactor it to be clear
Structured tags (@param, @return) enforce consistent, scannable documentationJournal comments: keeping a change log inside source files instead of using version control
⚖️ THE GOLDEN RULE
Think of commenting like adding road signs on a highway. Too few signs and drivers get lost. Too many signs and drivers stop reading any of them. The best signs appear at decision points—forks, exits, and unexpected turns—and they tell you why this route was chosen, not that you are on a road.

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.

From Javadoc basics to advanced software craft
ConceptWhat You Learn Now (Javadoc)Where It Leads (Advanced)
DocumentationWrite Javadoc comments on classes and methodsAPI documentation suites, OpenAPI/Swagger specs for web services
Design by ContractUse @param and @throws to describe expectationsFormal preconditions and postconditions, assertion frameworks
Self-Documenting CodeName variables and methods clearly to reduce the need for commentsClean Code principles, refactoring patterns, domain-driven design
Code ReviewsComments explain decisions to reviewersPull request descriptions, Architecture Decision Records (ADRs)
AnnotationsJavadoc tags add metadata to codeJava 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

PROBLEM 1 — CONCEPTUAL
A classmate writes the comment // multiply price by tax rate above the line double total = price * taxRate;. Explain why this comment is unhelpful and suggest a better one.
PROBLEM 2 — BASIC
Write a proper Javadoc comment for the following method signature: 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).
PROBLEM 3 — INTERMEDIATE
Consider this code snippet inside a method: 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.
PROBLEM 4 — APPLIED
You are building a student grade tracker application. Write a complete Javadoc comment for a method with this signature: 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.
PROBLEM 5 — CRITICAL THINKING
Some developers argue that "good code documents itself" and that comments are a "code smell" (a sign of problems). Others argue that comments are essential for professional code. Evaluate both positions. Under what circumstances are comments most valuable, and when might they indicate the code should be refactored instead? Give at least two examples of each scenario.

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.

Varsity Tutors • Java • Javadoc & Comments — Write Javadoc and comments that explain intent