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.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 5 figures

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

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.

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.

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.

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.

Java's Three Comment TypesSingle-Line //// This is a single-line// commentPurpose:Quick inline notesexplaining why aline or block exists.Where Used:Inside method bodiesnext to tricky logic.// Use binary search// because the list// is pre-sorted✓ Explains WHYMulti-Line /* *//* This is a multi-line comment */Purpose:Longer explanations,temporarily disablingcode blocks, or notes.Where Used:File headers, complexalgorithm explanations./* Retry up to 3x because the API is unreliable */✓ Explains WHYJavadoc /** *//** Javadoc comment * with @tags */Purpose:Public API docs thatgenerate HTML pages.The official contract.Where Used:Above classes, methods,constructors, fields./** Calculates tax * @param rate ... * @return total */✓ Formal Contract
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.

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

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

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.

Bad Comments vs. Good Comments✗ BAD — States the Obvious✓ GOOD — Explains Intent// set age to 18int age = 18;Repeats what the code clearly says// Legal voting age per US lawint minimumVotingAge = 18;Explains WHY the value is 18// loop through the arrayfor (int i = 0; i < arr.length; i++)Anyone can see it's a loop// Scan backwards to find the// most recent valid entryfor (int i = arr.length - 1; i >= 0; i--) /** Gets the name. */public String getName() { return this.name;}/** Returns the student's * full legal name as entered * during registration. */public String getName() {// TODO: fix this laterif (x > 0) { ... }Fix what? No context given.// TODO: Handle negative// balances (see ticket #42)if (balance > 0) { ... }Specific and traceable
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.

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. 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 @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. 2

    Step 2 — Document the Constructor

    The 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. 3

    Step 3 — Document a Public Method

    For 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. 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

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.

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 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

Strengths of good commenting vs. common pitfalls

⚖️

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.

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.

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

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

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.
Show answer
The comment merely restates what the code already expresses. Anyone who reads 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

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).
Show answer
A proper Javadoc comment would be: /** * 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

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.
Show answer
A good intent-explaining comment would be: // 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

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.
Show answer
A complete Javadoc comment would be: /** * 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

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.
Show answer
Both positions have merit, and the truth lies in their combination. Comments are most valuable when they explain design decisions ("We use a LinkedList here instead of ArrayList because insertions at the head dominate this workload"), business rules ("Discount capped at 30% per corporate policy"), workarounds for bugs ("Sorting twice works around a known JDK bug, see JDK-12345"), and non-obvious algorithmic choices. These are cases where no amount of renaming or refactoring can make the 'why' visible in the code. On the other hand, when you find yourself writing comments like "Check if the user is logged in" above 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.

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