Java 18 Code Snippets in Javadoc with @snippet

Introduction Good API documentation shows how to use the API, and the best way to show that is with code. Until Java 18, code examples in Javadoc comments were written with <pre>{@code ...}</pre>. This works, but has well-known problems: characters like @ and unbalanced braces need care, there is no way to highlight part of the example, and - worst of all - the examples are never compiled, so they quietly go out of date as the API changes. Java 18Click to read tutorial: Overview of New Features in Java 18 (JEP 413) added the @snippet tag for code examples in Javadoc. This tutorial explains @snippet with examples: inline snippets, markup to highlight and link parts of the code, and external snippets taken from real source files that the compiler checks. An inline snippet The simplest form is an inline snippet: {@snippet :, a newline, and then the code. The content may contain @ signs and HTML characters freely; only the braces must be balanced. Incidental indentation is removed, as in text blocks -
A class documented with @snippet
//Calculator.java
package demo;

/**
 * A tiny calculator.
 *
 * <p>Typical use:
 * {@snippet :
 * Calculator calc = new Calculator();
 * int sum = calc.add(2, 3);           // @highlight substring="add"
 * System.out.println(sum);            // prints 5
 * }
 *
 * <p>Annotations and generics need no escaping:
 * {@snippet :
 * @SuppressWarnings("unused")
 * List<Integer> results = List.of(calc.add(1, 1)); // @link substring="List.of" target="java.util.List#of()"
 * }
 */
public class Calculator {
  /**
   * Adds two numbers.
   *
   * {@snippet file="CalculatorExamples.java" region="add"}
   *
   * @param a the first number
   * @param b the second number
   * @return the sum of {@code a} and {@code b}
   */
  public int add(int a, int b) {
    return a + b;
  }
}
Markup: highlighting, links and replacements A snippet can contain markup tags in end-of-line comments of the form // @tag attributes. They control how the line is shown, and the markup comment itself is removed from the output -
  • @highlight - highlights text in the line, chosen with substring="..." or a regular expression with regex="...". Adding type="bold", italic or highlighted selects the style.
  • @link - turns text into a link to an API element, given with target, as in the List.of example above.
  • @replace - replaces text in the output, for example to show ... in place of code needed only to make the example compile: // @replace regex="sendRequest\(.*\)" replacement="...".
  • @start region=name and @end - mark a region of a file, used by external snippets.
A plain comment such as // prints 5 stays in the output as part of the example. External snippets from compilable code The add() method above uses an external snippet: {@snippet file="CalculatorExamples.java" region="add"}. The example is taken from a separate Java file - by default from a snippet-files directory next to the documented class - between the @start and @end markers. Because that file is ordinary Java code, it can be compiled and even run as a test, so the documentation fails to build, or the test fails, when the example breaks -
demo/snippet-files/CalculatorExamples.java
//CalculatorExamples.java
import demo.Calculator;

class CalculatorExamples {
  void examples() {
    // @start region="add"
    Calculator calc = new Calculator();
    int total = calc.add(40, 2);     // @highlight substring="add"
    assert total == 42;
    // @end
  }
}
Generating the documentation Snippets are processed by the javadoc tool. With the two files in place, the documentation is generated as usual -
javadoc -d docs --source-path src demo
The external snippet in the generated page for add() contains just the code of the region, with the markup comments removed - extracted here from the generated HTML -  The add() snippet in the generated HTML
Calculator calc = new Calculator();
int total = calc.add(40, 2);
assert total == 42;
In the browser, the highlighted add appears in bold, and the page offers a button to copy the snippet. The javadoc tool reports an error if a referenced file or region does not exist, so broken references are caught when the documentation is built. Summary In this tutorial we saw how Java 18's @snippet tag improves code examples in Javadoc. We wrote inline snippets which need no escaping, used markup comments to highlight text, link to API elements and replace text, and took an external snippet from a region of a real, compilable source file so that the example cannot silently go out of date. Lastly, we generated the documentation with javadoc and looked at the result. Java 23 later added Markdown documentation commentsClick to read: Markdown documentation comments, which work with @snippet too. Next, read about the deprecation of finalizationClick to read tutorial: Java 18 Deprecates Finalization: Use Cleaner Instead.