Javadoc: Writing Documentation Comments in Java
Write professional Java API documentation with javadoc: /** */ comments for classes, methods, fields and packages, @param, @return, @throws, @see and {@link}, {@code} and HTML, code snippets (Java 18), Markdown doc comments (Java 23), and generating HTML with the javadoc tool.
kvi5hnuCode Sprout team member13 min readOn this page
The JDK includes a tool called javadoc that generates HTML documentation from your source files. The official Java API documentation you've been browsing is simply the output of javadoc run on the standard library's source code.
If you add comments that start with the special delimiter /**, you can produce the same professional-looking documentation for your own code. The big advantage is that code and documentation live in one place. Documentation kept in a separate file tends to drift away from the code over time. When the comments sit next to the code, it's easy to update both and rerun javadoc. IDEs also show these comments as tooltips whenever someone uses your classes.
Where to Put Documentation Comments
javadoc extracts information about:
- modules,
- packages,
- public classes and interfaces,
- public and protected fields, and
- public and protected constructors and methods.
(Protected members are covered in the next part, interfaces in the one after, and modules in the last part.)
You can, and should, write a comment for each of these. Each comment goes immediately above the feature it describes. It starts with /** and ends with */. Ordinary // and /* ... */ comments are ignored by javadoc.

Each /** ... */ comment contains free-form text followed by tags:
- The first sentence of the free-form text should be a summary.
javadoccopies it into summary tables (the method summary of a class page, for instance). It ends at the first period followed by a space, so don't write "e.g. " in the first sentence; use{@summary ...}(Java 10+) for an explicit summary instead. - Block tags such as
@paramor@sincemust appear at the beginning of a line (optionally after whitespace,/**, or the leading*). They come after the description. - Inline tags can appear anywhere in the text and are enclosed in braces:
{@tagname contents}. Examples are{@code ...}and{@link ...}. The contents may contain braces, but they must be balanced.
Class Comments
A class comment goes after the import declarations, directly before the class:
/**
* A {@code Parcel} is one package handed to the courier, for example
* a 2.4 kg box going to Lisbon. It records the destination,
* the weight in kilograms and the delivery speed (standard or express).
*/
public class Parcel {
. . .
}
Method Comments
Each method comment must immediately precede its method. Besides the general tags, methods use:
| Tag | Meaning |
|---|---|
@param variable description | Adds an entry to the Parameters section. The description can span several lines and use HTML. Keep all @param tags of a method together, in parameter order. |
@return description | Adds a Returns section. |
@throws class description | Notes that the method may throw this exception, and when. (Exceptions are covered in a later part.) @exception is an older synonym. |
/**
* Increases this employee's salary by a percentage.
* @param pct the raise as a percentage of the current salary; 4 means 4%
* @return the amount of the raise
* @throws IllegalArgumentException if {@code pct} is negative
*/
public double giveRaise(double pct) {
if (pct < 0) throw new IllegalArgumentException("Negative raise: " + pct);
double raise = salary * pct / 100;
salary += raise;
return raise;
}
Constructors are documented the same way, with @param and @throws but no @return.
The inline {@return} tag
For simple accessors, the description and the @return text say the same thing:
/**
* Returns the employee's full name.
* @return the employee's full name
*/
Since Java 16, you can write it once with the inline form:
/**
* {@return the employee's full name}
*/
public String getName() { return name; }
javadoc expands it into the description "Returns the employee's full name." plus a Returns section saying the same.
Field Comments
You only need to document public fields, which usually means static constants:
/**
* Heaviest parcel the courier accepts, in kilograms.
*/
public static final double MAX_WEIGHT_KG = 30.0;
Private fields don't appear in the generated documentation (unless you run javadoc -private), but a short /** ... */ on them still helps readers of the source and shows up in IDE tooltips.
Package Comments
Class, method and field comments go into the Java source files. A package comment needs a separate file in the package directory. You have two choices:
-
package-info.java(preferred). It contains a documentation comment followed by thepackagedeclaration, and no other code or comments:java/** * Classes for a small payroll system: employees, managers and pay slips. * * <h2>General Principles</h2> * All amounts are stored in the smallest currency unit. */ package com.example.payroll; -
package.html, an HTML file. All text between<body>and</body>is extracted. (This is the legacy approach.)
package-info.java can also carry package-level annotations.
HTML Markup and Code
In the free-form text, you can use HTML: <em>...</em> for emphasis, <strong>...</strong> for strong emphasis, <ul>/<li> for bulleted lists, <p> for paragraphs, <h2>/<h3> for headings, and <img .../> for images.
For code in a monospaced font, use {@code ...} instead of <code>...</code>. Then you don't need to escape < and &: {@code List<String>} displays correctly, while <code>List<String></code> would be broken HTML. To display unescaped < or & in the normal font, use {@literal ...}.
For multi-line code examples, either wrap {@code} in a <pre> tag:
/**
* Typical usage:
* <pre>{@code
* var e = new Employee("Mira", 50000);
* e.giveRaise(4);
* }</pre>
*/
or, since Java 18, use the {@snippet} tag (JEP 413):
/**
* Typical usage:
* {@snippet :
* var e = new Employee("Mira", 50000);
* e.giveRaise(4); // @highlight substring="giveRaise"
* }
*/
Either way, < and & need no escaping. However, braces must be balanced, and the code can't contain /* ... */ comments, because */ would end the doc comment. {@snippet} is the modern choice: it supports highlighting and other markup, can include external files (below), and the generated page gets a Copy button. (For automatic syntax colouring of snippets and <pre><code> blocks, run javadoc with --syntax-highlight.)
Links
You can link to other parts of the documentation, or to external documents, with the @see and {@link} tags.
@see
@see reference adds a hyperlink in the See Also section. It works in class and method comments. The reference can take three forms:
@see com.example.payroll.Employee#giveRaise(double) // package.class#member label
@see <a href="https://openjdk.org/jeps/413">JEP 413: Code Snippets</a>
@see "The Java Language Specification"
package.class#member labelis the most useful.javadocinserts a link to that class, method or field. You can omit the package, or both package and class; then the current package or class is searched. Use#, not a period, between the class and the member. The compiler is clever about the many meanings of.(package separator, nested class, member access), butjavadocneeds help. For a method, give the parameter types:#giveRaise(double). For a constructor, use the class name as the method name:Employee#Employee(String, double). An optional label after the reference becomes the link text; without one, readers see the member name.- If
@seeis followed by<, you supply an HTML hyperlink to any URL. - If it's followed by
", the quoted text appears in the See Also section unlinked.
You can have several @see tags for one feature, but keep them together.
{@link} and {@linkplain}
To place a link anywhere in a comment, use the inline tag
{@link package.class#member label}
The reference follows the same rules as @see. The link is shown in code font. Use {@linkplain ...} for normal font.
Since Java 20, level 2 and level 3 headings automatically get IDs. <h2>General Principles</h2> gets the ID general-principles-heading. Link to such an ID with two # signs:
{@link com.example.payroll##general-principles-heading general principles}
General Tags
These tags can be used in class documentation comments and elsewhere:
| Tag | Purpose |
|---|---|
@since text | Adds a Since entry: the version that introduced the feature, e.g. @since 1.7.1. |
@author name | Adds an Author entry; use one tag per author. Shown only with javadoc -author. Version control tracks authorship more thoroughly, so many projects skip it. |
@version text | Adds a Version entry describing the current version. Shown only with javadoc -version. |
@deprecated text | Used together with the @Deprecated annotation. Explain when and why, and what to use instead (Use {@link #newMethod()} instead.). |
{@value optionalFormat constantRef} | Inserts the value of a constant. Since Java 20, a printf-style format is allowed: {@value %X Integer#MAX_VALUE} yields 7FFFFFFF. |
{@index entry} | Adds an entry to the generated index and search. |
{@inheritDoc} | Copies documentation from the overridden method (see the inheritance part). |
@spec url title | Links to an external specification (Java 20+). |
@hidden | Excludes an element from the generated documentation. |
Code Snippets from External Files
Code examples written inside comments are never compiled, so they go stale. The snippet feature (Java 18) lets you pull examples from real, compiled and tested source files instead. That reduces the risk of incorrect or outdated documentation.
To include an entire file:
{@snippet file=PayrollDemo.java}
{@snippet class=com.example.payroll.PayrollDemo}
Put such files in a snippet-files subdirectory of the current package (or point javadoc --snippet-path at another directory).
More commonly, you include only a region of a file. Mark it with @start and @end comments in the source:
public class PayrollDemo {
public static void main(String[] args) {
// @start region=raise
var e = new Employee("Mira", 50000); // @replace substring='"Mira", 50000' replacement="..."
double raise = e.giveRaise(4); // @highlight substring="giveRaise"
// @end
}
}
and reference it from the documentation comment:
/**
* Example:
* {@snippet file=PayrollDemo.java region=raise}
*/
The generated documentation shows
var e = new Employee(...);
double raise = e.giveRaise(4);
with giveRaise highlighted. The markup comments available:
| Markup comment | Effect |
|---|---|
// @start region=name … // @end | Defines a region to include |
// @highlight substring="text" or regex="..." | Highlights matching text (on this line, or in a region with region) |
// @replace substring="text" replacement="..." | Replaces text, for example to make an example more general |
// @link substring="Employee" target="Employee" | Turns text into a link to an API element |
Because all markup lives in ordinary comments, the source file still compiles and runs. Your examples can be part of your test suite.
Markdown Documentation Comments (Java 23+)
Writing HTML in comments is tedious. Since Java 23 (JEP 467), you can write documentation comments in Markdown. Each line starts with /// instead of using /** ... */:
/// Increases this employee's salary by a percentage.
///
/// The raise is added to the current salary. For example:
///
/// ```
/// var e = new Employee("Mira", 50000);
/// e.giveRaise(4); // salary is now 52000
/// ```
///
/// - Use whole percentages.
/// - Negative values are rejected.
///
/// @param pct the raise as a percentage of the current salary
/// @return the amount of the raise
/// @throws IllegalArgumentException if `pct` is negative
/// @see #getSalary()
public double giveRaise(double pct) { ... }
In Markdown comments:
`code`replaces{@code ...}, and fenced code blocks replace<pre>{@code ...}</pre>.*emphasis*,**strong**, lists, tables and headings use normal (CommonMark) Markdown.- Reference links in square brackets link to API elements:
[String],[#getSalary()],[java.util.List#add(Object)], or[the list][java.util.List]with custom text. - Block tags (
@param,@return, …) and inline tags ({@inheritDoc}) work as before.
If you're on Java 23 or later, Markdown comments are easier to write and read in the source. Traditional /** */ comments remain fully supported, and the JDK's own sources still mostly use them.
Generating the Documentation
Suppose docDirectory is where you want the HTML files to go:
-
Change to the directory that contains the source files. For nested packages such as
com.example.payroll, that's the directory containingcom(and anoverview.htmlfile, if you supply one). -
Run
bashjavadoc -d docDirectory nameOfPackagefor one package, or
javadoc -d docDirectory package1 package2 ...for several. For the unnamed package, runbashjavadoc -d docDirectory *.java
Without -d docDirectory, the HTML files are written into the current directory, which gets messy. Always use -d.
Useful options:
| Option | Effect |
|---|---|
-author, -version | Include @author and @version entries (omitted by default) |
-link https://docs.oracle.com/en/java/javase/25/docs/api/ | Link references to standard classes (String, List…) to the official online docs |
-linksource | Convert each source file to HTML with line numbers, and link class and method names to it |
-overview overview.html | Use the text between <body> and </body> as the Overview page |
--source-path dir | Where to find sources (and snippet-files) |
-private / -package | Also document private / package-access members (for internal docs) |
-Xdoclint:all | Check comments for missing tags, broken HTML and bad references |
-quiet | Show only warnings and errors |
A real run, with the Employee class and the snippet from above:
javadoc -d docs --source-path . -author -version -Xdoclint:all com.example.payroll
The docs directory then contains index.html, a page per class (com/example/payroll/Employee.html), the package summary, an index, and a search box (available since Java 9). For the complete list of options, see the javadoc tool guide in the JDK documentation.
In practice, build tools run javadoc for you: mvn javadoc:javadoc (Maven) or gradle javadoc (Gradle). Libraries published to Maven Central must include a -javadoc.jar.
Common questions
Should I write doc comments for private methods? They don't appear in the generated documentation by default, but a short comment explaining a non-obvious private method still helps maintainers, and IDEs show it in tooltips. Don't document trivial private helpers just for the sake of it.
Markdown (///) or classic /** */ comments?
On Java 23 or later, Markdown comments are easier to write and to read in the source. If your library must build its documentation with older JDKs, stay with /** */, because older javadoc versions treat /// as ordinary comments. Both styles can be mixed in one project.
How do I inherit documentation from an overridden method?
If an overriding method has no doc comment, javadoc copies the superclass's or interface's comment automatically. To add to it, write a comment and include {@inheritDoc} where the inherited text should go.
Why does my build fail with doclint errors?
Since Java 8, javadoc checks comments for broken HTML, unknown references and missing tags, and some build configurations treat those findings as errors. Fix the reported comments, or tune the checks with -Xdoclint:all,-missing. Don't simply turn doclint off: broken links in published docs frustrate users.
Do doc comments end up in the class files? No. They live only in the source code and the generated HTML. Annotations are a different mechanism: those with runtime retention are stored in class files and can be read with reflection.
Summary
javadocgenerates HTML API documentation from/** ... */comments placed directly above modules, packages, public classes, and public/protected members.- The first sentence is the summary. Block tags (
@param,@return,@throws,@see,@since,@deprecated,@author,@version) start a line; inline tags ({@code},{@link},{@linkplain},{@value},{@return},{@index}) go in braces. - Package comments go in
package-info.java. Images go indoc-files. - Use
{@code ...}for code; use<pre>{@code ...}</pre>or{@snippet}(Java 18) for multi-line examples. Snippets can include regions of real source files fromsnippet-files, with highlighting and replacements. - Links use
#before members:Employee#giveRaise(double). Java 20 adds##links to headings. - Java 23+ supports Markdown doc comments with
///. - Generate the docs with
javadoc -d docs packages..., or let Maven or Gradle do it.
Practice Questions
Which of these appear in the default javadoc output: a public method, a private field, a protected constructor, a package-access class?
The public method and the protected constructor. Private and package-access members are omitted unless you use -private or -package.
Write a javadoc comment for public static double average(int[] values) that throws IllegalArgumentException for an empty array.
/**
* Computes the arithmetic mean of the given values.
* @param values the values to average; must not be empty
* @return the average of {@code values}
* @throws IllegalArgumentException if {@code values} has length 0
*/
Why does Map<String, List<Integer>> inside an HTML code element render badly in javadoc, and what's the fix?
The < characters are parsed as HTML tags, so <String, and <Integer> are treated as (invalid) markup. Use {@code Map<String, List<Integer>>}, which escapes the content automatically.
How do you link to the method format(String, Object...) of class String from a doc comment?
{@link String#format(String, Object...)}, with # between class and method and the parameter types in parentheses. (In a Markdown comment: [String#format(String, Object...)].)
What's the main advantage of {@snippet file=... region=...} over a <pre>{@code} block?
The example comes from a real source file that's compiled (and can be tested), so the documentation can't silently go out of date. Markup comments also let you highlight, replace text and add links.
Where does the documentation comment for the package com.example.util go?
In com/example/util/package-info.java: a /** ... */ comment followed by package com.example.util;. The legacy alternative is package.html in the same directory.
Previous: Java JAR Files: Creating, Running and Configuring with the Manifest
Next: Java Class Design Hints: Writing Clean, Maintainable Classes
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.