Writing Javadoc Comments in Java with Examples

Introduction Every page of the official Java documentation - every description of String, List or Files - was generated from special comments in the JDK's source code, called Javadoc comments. You can document your own code the same way, and your IDE will show it as a tooltip wherever the code is used. This tutorial explains how to write Javadoc comments in Java, with examples. We will start with the format of a Javadoc comment and where it goes. We will then use the most important block tags - @param, @return, @throws and others - and the inline tags for code and links. Next we will generate HTML documentation with the javadoc tool, and let it check for missing documentation. Lastly, we will go through what makes documentation genuinely useful.

(Note - The three kinds of Java comments are introduced in Java Syntax BasicsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords.) The format of a Javadoc comment A Javadoc comment starts with /** - two asterisks - and ends with */. It is placed immediately before the class, interface, constructor, method or field it describes. It has two parts -
  • the description. Its first sentence is the summary, shown in method lists and tooltips, so it should stand on its own. It may contain HTML, such as <p> for a new paragraph.
  • the block tags, each starting with @ at the beginning of a line, after the description.
The structure of a Javadoc comment
/**
 * Returns the price after applying a percentage discount.     <- summary sentence
 * <p>
 * The discount is applied before tax. Prices are not rounded.  <- more description
 *
 * @param price    the original price; must not be negative     <- block tags
 * @param percent  the discount, from 0 to 100
 * @return the discounted price
 * @throws IllegalArgumentException if price is negative or percent is out of range
 */
public static double applyDiscount(double price, double percent) { ... }
The leading * on each line is optional, but conventional - the tool removes it. The main block tags
  • @param name description - one per parameter, in order. For a generic type parameter, write @param <T> description.
  • @return description - what the method returns; omitted for void methods and constructors.
  • @throws ExceptionType description - when each exception is thrown, for checked and important unchecked exceptions (@exception is an older synonym).
  • @see reference - a "See Also" link to a related class or method.
  • @since version - the version in which the element was added.
  • @deprecated explanation - why the element should no longer be used, and what to use instead; used together with the @Deprecated annotation, as explained in Deprecation in JavaClick to read tutorial on deprecation with @Deprecated and @deprecated.
  • @author and @version - for classes; less common in modern projects, where version control records this.
Inline tags - code and links inside the text Inline tags appear inside the description or a block tag's text, in curly braces -
  • {@code text} - shows text in code font, and displays < and > literally - {@code List}.
  • {@link Class#method(Type)} - a clickable link to another class or method; {@linkplain} is the same in normal font.
  • {@literal text} - text shown literally, without HTML interpretation.
  • {@inheritDoc} - copies the documentation of the overridden method.
  • {@snippet : ...} (Java 18+) - a properly formatted code example, replacing <pre>{@code ...}</pre>. See Code Snippets in Javadoc with @snippetClick to read tutorial on the Java 18 @snippet tag.
Here is a fully documented class -
A class documented with Javadoc
//PriceCalculator.java
import java.util.List;

/**
 * Utility methods for calculating order prices.
 * <p>
 * All amounts are in the shop's currency, as {@code double} values. For exact
 * money calculations, see {@link java.math.BigDecimal}.
 *
 * @since 1.0
 */
public final class PriceCalculator {

  /** The tax rate applied by {@link #withTax(double)}, as a fraction (0.18 means 18%). */
  public static final double TAX_RATE = 0.18;

  private PriceCalculator() {
  }

  /**
   * Returns the price after applying a percentage discount.
   *
   * @param price   the original price; must not be negative
   * @param percent the discount, from 0 to 100
   * @return the discounted price
   * @throws IllegalArgumentException if {@code price} is negative or {@code percent} is outside 0 to 100
   */
  public static double applyDiscount(double price, double percent) {
    if (price < 0 || percent < 0 || percent > 100) {
      throw new IllegalArgumentException("Invalid price " + price + " or percent " + percent);
    }
    return price * (100 - percent) / 100;
  }

  /**
   * Adds tax to a price, using {@link #TAX_RATE}.
   *
   * @param price the price before tax
   * @return the price including tax
   */
  public static double withTax(double price) {
    return price * (1 + TAX_RATE);
  }

  /**
   * Returns the sum of a list of prices.
   * {@snippet :
   * double total = PriceCalculator.total(List.of(9.99, 5.0)); // 14.99
   * }
   *
   * @param prices the prices to add; an empty list gives 0
   * @return the total of all prices
   * @see #withTax(double)
   */
  public static double total(List<Double> prices) {
    double sum = 0;
    for (double p : prices) {
      sum += p;
    }
    return sum;
  }

  /**
   * Prints two example calculations.
   *
   * @param args not used
   */
  public static void main(String[] args) {
    System.out.println(withTax(applyDiscount(100, 10)));
    System.out.println(total(List.of(9.99, 5.0)));
  }
}
 OUTPUT of the above code
106.19999999999999
14.99
Generating HTML with the javadoc tool The JDK's javadoc tool reads the source files and generates a website in the same style as the official Java API documentation. -d chooses the output directory.
javadoc -d apidocs -quiet PriceCalculator.java
dir /b apidocs
 OUTPUT of the above commands
allclasses-index.html
allpackages-index.html
constant-values.html
element-list
help-doc.html
index-all.html
index.html
legal
member-search-index.js
module-search-index.js
overview-tree.html
package-search-index.js
package-summary.html
package-tree.html
PriceCalculator.html
resource-files
script-files
search.html
tag-search-index.js
type-search-index.js
With -quiet and no problems in the comments, javadoc itself printed nothing; the listing shows what it generated. (On macOS and Linux, use ls apidocs.) Opening apidocs/index.html in a browser shows the class, its summary table of methods - each with its first sentence - and a detail page for every method with its parameters, return value and exceptions. Build tools generate the same documentation with mvn javadoc:javadoc or gradle javadoc - see Maven and GradleClick to read tutorial: Introduction to Maven and Gradle for Java Projects. Checking documentation with doclint javadoc also checks your comments, and the -Xdoclint option controls how strictly. Here is a class whose documentation has two common mistakes - a parameter which is not documented, and a public method with no comment at all.
A class with incomplete Javadoc
//Inventory.java
/**
 * Tracks stock levels.
 */
public class Inventory {
  private int stock;

  /** Creates an empty inventory. */
  public Inventory() {
  }

  /**
   * Adds items to the stock.
   *
   * @return the new stock level
   */
  public int add(int quantity) {
    stock += quantity;
    return stock;
  }

  public int stock() {
    return stock;
  }
}
 OUTPUT of javadoc -d lint-docs -quiet -Xdoclint:all Inventory.java
Inventory.java:17: warning: no @param for quantity
  public int add(int quantity) {
             ^
Inventory.java:22: warning: no comment
  public int stock() {
             ^
2 warnings
Each warning names the file, the line and the problem. Fixing them - adding @param quantity and a comment for stock() - makes the warnings disappear. Many projects run this check in their build, so that undocumented public APIs are caught early. Writing useful documentation
  • Document what, not how: describe what a method does, what it expects and what it guarantees - not the steps of its implementation, which can change.
  • Write a strong first sentence: it appears alone in summaries. "Returns the discounted price." beats "This method is used for discounts."
  • State the edge cases: whether null is allowed or returned, what happens with an empty list, units such as seconds or cents, and every exception.
  • Document every public and protected element - they are the API others use. Private helpers often need only a short comment, or none if their name says it all.
  • Do not repeat the name: /** Gets the name. */ on getName() adds nothing. Say something the signature cannot, or keep it short.
  • Keep it up to date: outdated documentation is worse than none. Change the comment in the same commit as the code.
Summary In this tutorial we first saw the format of a Javadoc comment - /** ... */ before the element, with a summary sentence, more description, and block tags. We then used the block tags @param, @return, @throws, @see, @since and @deprecated, and the inline tags {@code}, {@link} and {@snippet}, in a fully documented class. Next we generated HTML documentation with the javadoc tool, and found missing documentation with -Xdoclint:all. Lastly, we went through what makes documentation useful. In the next tutorial, we will find bugs by debugging Java programsClick to read tutorial: Debugging Java Programs in Your IDE and with jdb.