4 Markdown in Documentation Comments

Markdown is a widely used markup language for creating simple documents. It is easy to read, write, and can be easily converted into HTML.

Introduction

The standard doclet for the javadoc tool supports the use of the CommonMark variant of Markdown in documentation comments, along with extensions for JavaDoc Tags and Links to program elements.

To write a documentation comment using Markdown, use a series of adjacent end-of-line comments (see JLS: 3.7 Comments), in each beginning with three forward slashes (///). The content of the comment is then determined as follows:

  • Any leading whitespace and the three initial forward slash (/) characters are removed from each line.

  • The lines are then shifted left, by removing leading whitespace characters, until the non-blank line with the least leading whitespace characters has no remaining leading whitespace characters.

  • Additional leading whitespace characters and any trailing whitespace characters in each line are preserved.

The series of lines must be contiguous. For a blank line to be included in the comment, it must begin with any optional whitespace and then ///. A completely blank line will cause any preceding and following comment to be treated as separate comments. In that case, all but the last comment will be discarded, and only the last comment will be considered as a documentation comment for any declaration that may follow.

For example,


/// This is the traditional "Hello World!" program.
public class HelloWorld {
    public static void main(String... args) {
        System.out.println("Hello World!");
    }
}
In such a comment, you can use simple Markdown inline formatting. For example,
/// This is the traditional _"Hello World!"_ program.
will generate the following output:
<p>This is the traditional <em>"Hello World!"</em> program.</p>

Links

To create a link to an element declared elsewhere in your API, you can use an extended form of a Markdown reference link, in which the label for the reference is derived from a reference to the element itself.

To create a link whose text is derived from the identity of the element, enclose a reference to the element in square brackets. For example, to link to java.util.List, write [java.util.List], or just [List] if there is an import statement for java.util.List in the code. The text of the link will be displayed in monospace font. The link is equivalent to using the standard JavaDoc {@link ...} tag.

You can link to any kind of program element, as shown in the following examples:
/// * a module [java.base/]
/// * a package [java.util]
/// * a class [String]
/// * a field [String#CASE_INSENSITIVE_ORDER]
/// * a method [String#chars()]

To create a link with alternative text, use the form [text][element]. For example, to create a link to java.util.List with the text a list, write [a list][List]. The link will be displayed in the current font, although you can use formatting details within the given text. The link is equivalent to using the standard JavaDoc {@linkplain ...} tag.

For example,

/// * [the `java.base` module][java.base/]
/// * [the `java.util` package][java.util]
/// * [a class][String]
/// * [a field][String#CASE_INSENSITIVE_ORDER]
/// * [a method][String#chars()]

To create a reference link to a method that has array parameters, you must escape the square brackets within the reference. For example, here is a reference link to the method String.copyValueOf(char[]):

[String#copyValueOf(char\[\])]

To create a link to user-defined and implicitly defined IDs in the generated documentation use the ## notation. For example, the Java SE class MemoryLayout has a heading Access mode restrictions with a corresponding anchor access-mode-restrictions. The following example shows a link to that anchor:

/// link to [access mode restrictions][MemoryLayout##access-mode-restrictions]

You can also use other forms of Markdown links; however, links to other program elements are generally the most common.

Tables

Simple tables are supported using the syntax defined in GitHub Flavored Markdown Spec. For example, a simple table might be written as follows:

/// | Latin | Greek |
/// |-------|-------|
/// | a     | alpha |
/// | b     | beta  |
/// | c     | gamma |

Captions and other features that may be required for accessibility are not supported. In such situations, the use of HTML tables is still recommended.

JavaDoc Tags

JavaDoc tags, both inline tags (like {@inheritDoc}) and block tags (like @param and @return), may be used in Markdown documentation comments, although neither may be used within literal text, such as in a code span, which is inline text enclosed within backticks, or a code block, which is a block of text that is either indented code block or enclosed within fences, like three backticks (```) or three tildes (~~~).

For example, the following shows how JavaDoc tags can be mixed with Markdown:
/// {@inheritDoc}
/// In addition, this methods calls [#wait()].
///
/// @param i the index
public void m(int i) ...

The following examples illustrate that the character sequences @... and {@...} have no special meaning within code spans and code blocks:

/// The following code span contains literal text, and not a JavaDoc tag:
/// `{@inheritDoc}`
///
/// In the following indented code block, `@Override` is an annotation,
/// and not a JavaDoc tag:
///
///     @Override
///     public void m() ...
///
/// Likewise, in the following fenced code block, `@Override` is an annotation,
/// and not a JavaDoc tag:
///
/// ```
/// @Override
/// public void m() ...
/// ```

For those tags that may contain text with markup, in a Markdown documentation comment, that markup will also be in Markdown format.

For example, the following shows the use of Markdown within a JavaDoc @param tag:

/// @param the list, or `null` if no list is available

The {@inheritDoc} tag is used to include documentation for a method from one or more supertypes. The format of the comment containing the tag does not need to be the same as the format of the comment containing the documentation to be inherited.

For example,

interface Base {
    /** A method. */
    void m()
}

class Derived implements Base {
    /// {@inheritDoc}
    public void m() { }
}

User-defined JavaDoc tags may be used in Markdown documentation comments as well as the standard JavaDoc tags. For example, in the JDK documentation, {@jls ...} is used and defined as a short form for links to the Java Language Specification (JLS). In addition, block tags like @implSpec and @implNote introduce sections of particular information.

/// For more information on comments, see {@jls 3.7 Comments}.
///
/// @implSpec
/// This implementation does nothing.
public void doSomething() { }

Code Examples

Code examples can be included in a documentation comment either by using Markdown code spans or code blocks, or by using {@snippet …} tags. While code spans and code blocks are simple and familiar, snippet tags provide additional functionality, such as linking to other program elements within the generated documentation.

In contrast to the use of traditional comments (see JLS: 3.7 Comments), there are no restrictions on the characters that may appear after the /// on each line. In particular, there are no restrictions on the use of */ in end-of-line comments.

For example, you can include either kind of comments in source code examples:

/// Here is an example of how to use this method.
/// 
/// /* get the next random number */
/// var i = rgen.nextInt(); 
/// 
int nextInt();
or
/// Here is an example of how to use this method.
/// 
/// // get the next random number
/// var i = rgen.nextInt(); 
/// 
int nextInt();

The characters */ may also show up in examples containing regular expressions:

/// 
/// // Find all strings ending in '.*/'
/// return strings.stream().filter(s-> s.matches(".*/"));
/// 

These characters may also show up in examples containing glob expressions:

/// ```
/// // Find all paths for .txt files in home directories.
/// return Files.newDirectoryStream(dir, "/home/*/*.txt");
/// ```

Headings

Both setext and ATX headings are supported in Markdown documentation comments. Headings should start at level 1 and increase from there. The level will adjusted automatically as appropriate when the content of the comment is included in the generated documentation.
/// Introductory paragraph.
///
/// # Additional details
/// Here are some additional details
/// 
/// # Summary
/// Here is a summary of the important details.

HTML

Markdown allows careful use of HTML for markup that is not directly supported by Markdown. Markdown differentiates between inline HTML (such as for <span ...>...</span> or <sup>...</sup>) and HTML blocks (such as for tables and definition lists).
/// This is the traditional <span id="hw">Hello World!</span> program.

You can also use HTML entities for characters outside the character set used for the source code:

/// This is the traditional &ldquo;Hello World!&rdquo; program.

Note that Markdown syntax is not recognized within HTML blocks, although you may use Markdown syntax in paragraphs or other blocks between HTML blocks. For more details, see the sections HTML blocks and Raw HTML in the CommonMark specification. JavaDoc tags are supported in HTML blocks.

Standalone Markdown files

Markdown files in doc-files subdirectories are processed appropriately, in a similar manner to HTML files in such directories. JavaDoc tags in such files will be processed. The page title will be inferred from the first heading. YAML metadata, such as that supported by Pandoc's Markdown processor (see the section Pandoc's Markdown in Pandoc User's Guide), is not supported.

The file containing the content for the generated top-level ("overview") page may also be a Markdown file.

Errors

Except for any use of JavaDoc tags, any other sequence of characters in a Markdown documentation comment is a valid CommonMark document. In other words, no errors will be reported for any sequence of characters that an author might regard as a malformed Markdown construct. Typically, any such sequence of characters will appear in the generated output as plain literal text.

Any issues found in the use of JavaDoc tags in a Markdown documentation comment may result in diagnostic messages reported to the console or distinctive content, such as the following, placed in the generated documentation:

HTML Source Rendered HTML
<span style="border:1px solid black; background-color:#ffe6e6; padding: 2px">&#x25B6; invalid @code</span>
Invalid code image

As with traditional (non-Markdown) documentation comments, it is recommended that authors carefully proofread the documentation generated by the javadoc from their documentation comments to ensure that the generated output is as intended.