01 / 21

Javadoc &
Comments

Learn to write Javadoc and comments that explain the intent behind your code: not what it does, but why it does it.

Java

Why Comments Matter

Code is read far more often than it is written. Six months from now, you (or a teammate) will re-open your file and need to understand why a decision was made: not just what the syntax does.

Java gives you three distinct tools for this job. Each has a different audience and purpose. Mastering them means your code communicates on every level.

The Three Comment Types

// Single-Line
Quick notes beside or above a line. Ideal for explaining why a specific statement exists.
/* */ Multi-Line
Longer explanations spanning multiple lines. Use for algorithm descriptions or complex logic blocks.
/** */ Javadoc
Special documentation comments parsed by the javadoc tool. Generates browsable HTML API docs.

Anatomy of a Javadoc Comment

/** ← Opening delimiter * Calculates the area of a circle. Summary line * * Uses the standard formula with * Math.PI for precision. Detail paragraph * * @param radius the circle's radius Block tags * @return the computed area * @throws IllegalArgumentException * if radius is negative */ ← Closing delimiter

The Core Rule

✕ Bad: What
// increment i by 1
i++;
✓ Good: Why
// skip the header row
i++;

The first comment is pure noise: any Java reader knows i++ increments. The second comment reveals intent: we skip a row because it is a header.

Essential Javadoc Tags

Tag Purpose Placement
@param Describes a method parameter Methods, constructors
@return Describes the return value Non-void methods
@throws Documents an exception thrown Methods that throw
@author Names the author Classes, interfaces
@version Version number of the class Classes
@see Cross-reference to related class/method Anywhere
@deprecated Marks element as outdated Any documented element

Javadoc vs Implementation Comments

Aspect Javadoc /** */ Implementation // or /* */
Audience Users of your API Developers reading the source
Placement Before class, method, or field Inside method bodies
Tool support Parsed by javadoc tool Ignored by all tools
Focus Contract: what, params, return Intent: why this approach
Appears in IDE Hover tooltips, autocomplete Only when viewing source

Step-by-Step Writing Process

1
Write the method signature first. Name it clearly enough that a reader gets the gist without any comment.
2
Add the Javadoc summary line. One sentence: what does this method do for its caller? Start with a verb phrase.
3
Document every parameter with @param. Describe constraints: can it be null? Must it be positive?
4
Document the return value with @return. State what the caller receives and any edge cases.
5
Document exceptions with @throws. Explain the condition that triggers each exception.
6
Add inline comments inside the body only where the why is non-obvious. Resist explaining the what.

Example 1: Basic Method

/** * Converts a temperature from Fahrenheit to Celsius. * * @param fahrenheit the temperature in degrees Fahrenheit * @return the equivalent temperature in degrees Celsius */ public static double toCelsius(double fahrenheit) { return (fahrenheit - 32) * 5.0 / 9.0; }

Example 2: Handling Edge Cases

/** * Returns the index of the target in the sorted array, * or -1 if the target is not found. * * Uses binary search for \(O(\log n)\) performance. * * @param arr a sorted array; must not be null * @param target the value to search for * @return index of target, or -1 if absent * @throws NullPointerException if arr is null */ public static int binarySearch(int[] arr, int target) { // low and high define the current search window int low = 0, high = arr.length - 1; while (low <= high) { // avoid overflow vs (low + high) / 2 int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }

Example 3: Class-Level Javadoc

/** * A thread-safe bounded queue backed by a circular array. * * Producers block when the queue is full; consumers block * when it is empty. This avoids busy-waiting and reduces * CPU usage compared to a spin-lock approach. * * <p>Usage example: * <pre> * BoundedQueue<String> q = new BoundedQueue<>(16); * q.put("hello"); * String s = q.take(); * </pre> * * @param <E> the type of elements in this queue * @author Jane Doe * @version 2.1 * @see java.util.concurrent.ArrayBlockingQueue */ public class BoundedQueue<E> { ... }

When to Write Which Comment

New code element? Is it a public API? YES Write Javadoc /** summary + tags */ NO Non-obvious logic? YES Inline comment // explain the WHY NO No comment needed Let the code speak

Writing Great Summary Lines

1
Start with a third-person verb. "Calculates...", "Returns...", "Validates...": not "This method calculates...".
2
Keep it to one sentence. The first sentence becomes the summary in generated API documentation.
3
End with a period. The javadoc tool uses the first period to delimit the summary from the detail paragraph.
4
Avoid repeating the method name. getName() documented as "Gets the name" adds zero information. Say what name and why it matters.

Inline Comments: Less Is More

Inline comments (//) are powerful when used sparingly. Reserve them for lines where the reasoning is invisible from the code alone.

✓ Good Uses
Explaining a workaround, noting a performance trick, clarifying a non-obvious constant, referencing a bug ticket
✕ Bad Uses
Restating what the code does, commenting every single line, leaving TODO comments in production code, outdated notes

Common Mistakes

✕ Narrating the Code
Writing // set x to 5 above x = 5; adds nothing. Describe intent, not mechanics.
✕ Missing @param Tags
Leaving parameters undocumented means callers must read your source to learn constraints and types.
✕ Stale Comments
Changing the code without updating the comment creates a lie that misleads every future reader.
✕ Javadoc on Private Methods
Private methods are not part of the public API. Use simple inline comments instead: Javadoc here is wasted effort.

Quick Reference Summary

Question Answer
When to use /** Before every public class, method, constructor, and field
When to use // Inside method bodies where the why is non-obvious
When to use /* */ Multi-line internal notes, algorithm explanations, or license headers
What to comment Intent, constraints, edge cases, design trade-offs
What NOT to comment What the code literally does, obvious getter/setter logic
Summary line style Third-person verb phrase, one sentence, ends with a period
Maintenance rule Update the comment every time you change the code

Question 1 of 5

Which comment type is parsed by the javadoc tool to generate HTML documentation?

Question 2 of 5

What is wrong with the comment above?

Question 3 of 5

Which Javadoc tag should you use to document a method parameter?

Question 4 of 5

A Javadoc summary line should begin with which of the following?

Question 5 of 5

What is the best commenting strategy for this method?