Javadoc in Java

Naveen AnamaneniUpdated · 8 min read

When you buy a new washing machine, the manual tells you what each button does, what you must never put inside, and what the warning lights mean. You don't need to know how the motor is wired. Javadoc is that manual for Java code: it explains what each class and method does, what it expects and what it returns, so other programmers can use it without reading the code. The JDK's own documentation at docs.oracle.com is generated by exactly this tool. In this lesson, you will learn the Javadoc tags, how to document a package, how to add code samples and deprecation notes, and how to run the javadoc command. The basics of comments are in "Java Comments", and the Markdown style is in "Markdown Documentation Comments in Java".

What Is Javadoc?

Javadoc is a JDK tool, and a comment format, that is used to generate HTML documentation from documentation comments in Java source code. A documentation comment starts with /** (or with /// lines in Markdown style) and sits directly before a class, interface, constructor, method or field.

  • The first sentence becomes the summary shown in tables and search results.
  • The rest of the text becomes the full description.
  • Block tags such as @param and @return fill the standard sections.
  • Only public and protected members appear by default, because they form the API.

Block Tags

Block tags go at the end of the comment, each on its own line.

TagDescription
@param name textIt is used to describe one parameter. Write one for every parameter.
@return textIt describes the return value. Leave it out for void methods.
@throws Type textIt describes when an exception is thrown (@exception is an older synonym).
@see referenceIt adds a "See Also" link to another class, method or URL.
@since versionIt records the version in which the element was added.
@deprecated textIt explains why the element shouldn't be used and what to use instead.
@author nameIt names the author (shown only with the -author option).
@version textIt gives the class's version (shown only with the -version option).

Inline Tags

Inline tags appear inside the text, in curly braces.

TagDescription
{@code text}It is used to show code in a code font without HTML interpreting < and >.
{@link Class#method}It creates a link to another element, shown in code font.
{@linkplain Class#method label}It creates a link shown in normal text.
{@inheritDoc}It copies the description from the method being overridden.
{@snippet : ... }It includes a code sample (Java 18+), with optional highlighting and checks.
{@value #CONSTANT}It shows the value of a constant.

A Documented Class

Let's see a fully documented class from a package school.fees.

FeeCalculator.java
package school.fees;
 
/**
 * Calculates the fee a student pays for one term.
 *
 * <p>Example:
 * {@snippet :
 * FeeCalculator calc = new FeeCalculator(500);
 * int due = calc.totalFee(15000, 3); // 16500
 * }
 *
 * @author Navika Anamaneni
 * @version 1.2
 * @since 1.0
 * @see Discount
 */
public class FeeCalculator {
    private final int finePerDay;
 
    /**
     * Creates a calculator.
     *
     * @param finePerDay the fine added for each late day, in rupees
     * @throws IllegalArgumentException if {@code finePerDay} is negative
     */
    public FeeCalculator(int finePerDay) {
        if (finePerDay < 0) {
            throw new IllegalArgumentException("finePerDay < 0");
        }
        this.finePerDay = finePerDay;
    }
 
    /**
     * Returns the fee including any late fine.
     *
     * @param baseFee  the term fee, in rupees
     * @param lateDays how many days late the payment is; 0 if on time
     * @return the total amount to pay
     */
    public int totalFee(int baseFee, int lateDays) {
        return baseFee + lateDays * finePerDay;
    }
 
    /**
     * Returns the fee without fines.
     *
     * @param baseFee the term fee
     * @return the same fee
     * @deprecated Use {@link #totalFee(int, int)} with 0 late days.
     */
    @Deprecated(since = "1.2")
    public int fee(int baseFee) {
        return baseFee;
    }
 
    public int finePerDay() {
        return finePerDay;
    }
}

Explanation:

  1. The class comment's first sentence, "Calculates the fee a student pays for one term.", becomes its summary.
  2. {@snippet : ... } shows a code example. Unlike a <pre> block, it handles <, > and @ safely and can highlight parts.
  3. The constructor documents its parameter and the exception it can throw; {@code finePerDay} shows the name in code font.
  4. The old fee method has both the @deprecated tag (which explains what to use instead) and the @Deprecated annotation (which makes the compiler warn callers). Use them together.
  5. finePerDay() has no comment on purpose, to show the warning below.

Documenting a Package

A package gets its documentation from a file named package-info.java in the package folder:

package-info.java
/**
 * Classes for calculating school fees, fines and discounts.
 *
 * @since 1.0
 */
package school.fees;

For a module, put the comment above the module declaration in module-info.java. For a whole project, an overview.html file passed with -overview adds a front page.

Running the javadoc Command

With the sources in src/school/fees (FeeCalculator.java, Discount.java and package-info.java), generate the documentation into a docs folder:

Terminal
javadoc -d docs -sourcepath src -author -version -subpackages school
Terminal output
Loading source files for package school...
Constructing Javadoc information...
Creating destination directory: "docs/"
Building index for all the packages and classes...
Standard Doclet version 25.0.5.0.3
Building tree for all the packages and classes...
Generating docs/school/fees/Discount.html...
Generating docs/school/fees/FeeCalculator.html...
src/school/fees/FeeCalculator.java:56: warning: no comment
    public int finePerDay() {
               ^
Generating docs/school/fees/package-summary.html...
Generating docs/school/fees/package-tree.html...
Generating docs/overview-tree.html...
Generating docs/deprecated-list.html...
Generating docs/allclasses-index.html...
Building index for all classes...
Generating docs/allpackages-index.html...
Generating docs/index-all.html...
Generating docs/search.html...
Generating docs/index.html...
Generating docs/help-doc.html...
1 warning

Explanation: open docs/index.html in a browser. You get a page per class, a package summary with the text from package-info.java, a search box, an index, and a Deprecated list that includes fee. The warning points to the public method with no comment. javadoc checks comments with doclint, which also warns about missing @param tags, broken links and bad HTML.

OptionDescription
-d dirIt is used to set the output folder.
-sourcepath pathIt tells javadoc where the source folders are.
-subpackages pkgIt documents a package and all packages below it.
-author, -versionThey include @author and @version text (left out by default).
-privateIt also documents private members, for internal docs.
-link urlIt links types such as String to the online JDK docs.
-Xdoclint:all / -Xdoclint:noneThey turn every check on, or turn checks off.
-overview fileIt adds an overview front page.

Writing Good Javadoc

DoDon't
Start with a verb in the third person: "Returns...", "Calculates..."Repeat the method name: "getFee gets the fee."
Say what the method does and its rules (units, limits, null handling)Describe how the code works line by line
Document every exception a caller can act onList every RuntimeException the code might ever throw
Use {@code} for code words and {@link} for related APILeave comments that no longer match the code
Document public and protected API thoroughlyWrite long Javadoc for obvious private helpers

Common Mistakes

Putting the comment after an annotation. The doc comment must come before any annotations: first /** ... */, then @Deprecated, then the method.

Using /* instead of /**. A normal block comment is ignored by javadoc.

< and > in plain text. They are read as HTML tags. Write {@code List<String>}.

@deprecated without an alternative. Always say what to use instead and since which version.

Practice

  1. Easy: Add a comment to finePerDay() in the example, run javadoc again, and check that the warning disappears.
  2. Harder: Write a class Discount implementation called SiblingDiscount that overrides apply, and use {@inheritDoc} plus one extra sentence. Generate the docs with -link https://docs.oracle.com/en/java/javase/25/docs/api/ and check that int and Override links work.

Quick check: Javadoc

4 questions
1Where does the summary of a doc comment come from?
2Which file documents a package?
3How do you show List safely in Javadoc text?
4What should accompany @deprecated?

Key Takeaways

Was this tutorial helpful?

Lesson 533 of 578