Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 201 ยท Getting Started

Comments and Javadoc

Learn Java's comment styles - // and /* */, Javadoc with @param and @return, Markdown doc comments with /// (Java 23+) - and the habits that make comments useful.

A comment is text in your source code that the compiler ignores. Comments are written for humans: your teammates, the people who will maintain your code years from now, and you, three months from now, wondering why you wrote that line.

Java has three kinds of comment. Two are ordinary notes, and the third, the documentation comment, is read by the javadoc tool to produce the browsable API documentation every Java library ships with. This lesson covers all three, including the Markdown style of documentation comment added in Java 23, and ends with the habits that separate helpful comments from noise.

Single-line comments: //

Two slashes // start a comment that runs to the end of the line. You can put it on its own line, above the code it explains, or at the end of a line of code:

Java Single-line comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the last two lines. Putting // in front of a line of code comments it out: the code stays in the file but doesn't run, which is handy while experimenting. And // inside a string literal is not a comment at all; it's part of the text. Java decides what's a comment before it looks at anything else, and string literals are the one place comment markers lose their meaning.

Tip: In almost every editor and IDE, Ctrl + / (Cmd + / on macOS) comments out the selected lines with //, and pressing it again removes them. Try it in the editor above.

Block comments: /* ... */

A block comment starts with /* and ends with */. Everything in between is ignored, across as many lines as you like. Block comments can also sit in the middle of a line:

Java Block comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The asterisks at the start of each inner line are not required. They're a widely used convention that makes the comment's extent easy to see.

Block comments don't nest

A block comment ends at the first */, no matter how many /* came before it. That makes it risky to comment out a chunk of code that already contains a block comment:

Java Block comments can't nest (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The comment ends at inner comment */, so Java tries to read line 4 as code and reports ';' expected four times. For commenting out code, use // on each line instead. Line comments can't collide like this, and editors add them for you.

Documentation comments: /** ... */

A comment that starts with /** (two asterisks) is a documentation comment, usually called a Javadoc comment. To the compiler it's still just a comment. But when it sits directly before a class, method, field or constructor, the javadoc tool collects it into HTML documentation, and IDEs show it in a pop-up whenever you hover over or auto-complete that name.

A Javadoc comment has two parts. First comes a description, whose first sentence is used as a short summary in lists. Then come block tags that start with @:

Java A method with a Javadoc comment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The most useful tags and inline tags:

Tag Meaning
@param name description Describes one parameter. Write one per parameter, in order.
@return description Describes the returned value. Omit it for void methods.
@throws Type description Describes an exception the method can throw, and when.
@see Reference Points readers to a related class or method.
@since version The version in which this item was added.
@deprecated explanation Says the item shouldn't be used anymore, and what to use instead. Pair it with the @Deprecated annotation.
{@code text} Inline: shows text in code font, without treating < and > as HTML.
{@link Class#method} Inline: a clickable link to another documented item.

Traditional Javadoc comments are written in HTML, which is why the example uses <p> to start a new paragraph. A blank line alone doesn't make a paragraph break in this style.

You generate the documentation with the javadoc tool that comes with the JDK:

Terminal
javadoc -d docs Main.java

This creates a docs folder of HTML pages that look just like the official Java API documentation. Build tools like Maven and Gradle run it for you; see Build Tools: Maven and Gradle.

Markdown documentation comments: /// (Java 23+)

Writing HTML inside comments is clumsy, so Java 23 introduced a second style of documentation comment written in Markdown. Each line starts with three slashes ///:

Java
/// Calculates the price after a percentage discount.
///
/// The discount is applied to the full price, and the result
/// is rounded down to a whole number of cents.
///
/// @param priceInCents the original price, in cents
/// @param percent      the discount, from 0 to 100
/// @return the discounted price, in cents
/// @throws IllegalArgumentException if `percent` is outside 0..100
static int discounted(int priceInCents, int percent) { ... }

Inside a /// comment you use Markdown instead of HTML:

  • A blank /// line starts a new paragraph (no <p> needed).
  • `backticks` format code, replacing {@code ...}.
  • - or * start bullet lists, and **bold** and _italic_ work as usual.
  • A name in square brackets, such as [String] or [List#of()], becomes a link, replacing {@link ...}.
  • The @param, @return and @throws block tags work exactly as before.

The JDK's own javadoc tool is available on our server, so you can watch it turn a Markdown comment into documentation. This program writes a small class to a temporary folder, runs javadoc on it, and prints the text of the generated page for the method:

Java Generate documentation from a /// comment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output contains the method signature, the description with the Markdown converted, and the "Parameters" and "Returns" sections built from the tags. That's exactly what an IDE shows when you hover over toFahrenheit.

Note: /// comments need Java 23 or later for javadoc to treat them as documentation. Older tools see them as ordinary // comments, so they never break compilation. Many existing projects still use /** */, and both styles can be mixed in one file. Pick one per project for consistency.

Where documentation comments belong

A documentation comment only counts when it comes immediately before a declaration: a class, interface, record, enum, field, constructor or method. Annotations like @Override may sit between the comment and the declaration. A /** comment inside a method body, such as above a local variable, is just an ordinary comment that the javadoc tool ignores. Document what callers need: public and protected members first. Private helpers rarely need full Javadoc.

A hidden trap: \u in comments

Here's a surprise that catches even experienced developers. Before the compiler does anything else, including finding comments, it translates Unicode escapes: \u followed by four hexadecimal digits, such as \u0041 for the letter A. That translation applies to the whole file, comments included. So a comment containing a lowercase \u that isn't followed by four hex digits breaks compilation:

Java A Windows path in a comment (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports illegal unicode escape on line 2, inside what looks like a harmless comment. The fixes are easy: write the path with forward slashes, or capitalize Users (only a lowercase \u starts an escape). It's rare, but now you'll recognize it instantly.

Good comment habits

Comments can make code dramatically easier to understand, or they can clutter it with noise that slowly turns into lies. A few habits keep them on the helpful side.

Explain why, not what. The code already says what happens. A comment earns its place by saying why:

Java
// Bad: repeats the code
count = count + 1;   // add one to count

// Good: explains a decision the code can't express
// Retry once: the payment gateway often drops the first request after idling.
retries = 1;

Prefer clear code over comments. If you need a comment to explain what a variable holds, rename the variable. int d; // elapsed days is weaker than int elapsedDays;. If a block needs a heading comment, consider moving it into a well-named method.

Keep comments true. A wrong comment is worse than none, because readers trust it. When you change code, update or delete the comments around it.

Document public APIs. Every public class and method that other people will call deserves a documentation comment that explains what it does, what its parameters mean, what it returns and when it fails. That's the contract they program against.

Don't leave dead code. Commenting out code is fine while you experiment, but don't commit it. Version control (like Git) remembers old code for you.

Mark unfinished work consistently. Many teams use // TODO: for work still to be done and // FIXME: for known problems. IDEs list these markers so they're easy to find later.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this line print? IO.println("a // b"); // c

    Inside a string literal, // is ordinary text. The comment starts only at the second //, after the closing parenthesis and semicolon.
  2. 2. Why does wrapping code that already contains a /* ... */ comment in another /* ... */ often fail?

    Block comments don't nest. The first */ closes the comment, and whatever follows is compiled as code. Use // lines to comment out code.
  3. 3. Which tag documents the value a method gives back?

    @return describes the returned value. @param describes a parameter, @throws an exception, and @see points to related items.
  4. 4. In a Markdown documentation comment (///), how do you start a new paragraph?

    Markdown doc comments use normal Markdown rules, so a blank line separates paragraphs. The <p> tag is the habit of traditional HTML-based /** */ comments.
  5. 5. Which comment is the most useful?

    Good comments explain why or add knowledge the code can't express. The others merely repeat what the code already says.

Summary

  • // comments run to the end of the line; use them for short notes and to comment out code.
  • /* ... */ block comments span lines but don't nest: they end at the first */.
  • /** ... */ Javadoc comments before a declaration become API documentation. They use HTML plus tags like @param, @return, @throws, {@code} and {@link}.
  • Java 23+ adds Markdown doc comments with ///: blank lines for paragraphs, backticks for code, [Name] for links.
  • The compiler translates \u escapes everywhere, even in comments, so a lowercase \u in a comment can break compilation.
  • Comment why, not what; prefer clear names; keep comments true; document public APIs.

Next: Printing Output, where you'll master println, print, escape sequences and formatted output with printf.