Topic 14 of 119 2. Fundamentals of Java Programming Interactive Tutorial

Java Comments: Single-Line, Multi-Line, and Documentation Comments

10 mins read Last updated: 22 Aug 2026 17,422 views

Direct Answer & Core Concept

Java has exactly three comment syntaxes, and each one answers a different question.

The single-line comment starts with two slashes and ends at the end of the line. Use it to explain one idea next to one line of code. The multi-line comment is wrapped in slash-star and star-slash. Use it for a longer explanation or to temporarily disable a block while debugging. The documentation comment, written as slash-star-star, looks similar but behaves differently: it is not just a comment, it is structured input that the javadoc tool reads to build searchable HTML documentation.

Three details trip up almost everyone. Block comments do not nest, so you cannot wrap commented-out code that itself contains a block comment. A block comment can sit in the middle of an expression, which is occasionally useful but makes code harder to read. And javadoc comments are only collected when they sit immediately before the declaration they document, so a blank line between the comment and the class silently drops it from the documentation.

Finally, remember that comments are stripped by the compiler and never reach the bytecode, so a comment cannot slow your program down. That is exactly why commenting out code is a debugging technique rather than a performance mistake, and also why commenting out code you never delete is a maintenance problem rather than a performance one.

Detailed Explanation & Mechanics

1) Single-Line Comments: // to End of Line

int timeout = 30; // seconds, not milliseconds

Everything after the two slashes is ignored until the newline. You can place one on its own line above code, or after code on the same line. There is no block form of a single-line comment and no way to end it early.

2) Multi-Line Comments: /* ... */

/* This comment
can span many
lines and stops only at the first star-slash. */

The closing token is the first star-slash that appears. That word "first" is the source of the biggest gotcha in this topic.

3) Documentation Comments: /** ... */

/**
* Adds two numbers.
* @param a first operand
* @return the sum
*/

The extra star is what makes this a documentation comment rather than an ordinary block comment. The javadoc tool reads these and produces HTML. They must sit directly above a class, method, field, or constructor with no blank line in between.

4) The Nesting Rule, Which Is the Part Everyone Misses

Block comments do not nest. The first star-slash closes the comment, whatever follows is treated as code. So this fails to compile:

/* trying to disable this
/* and this too */
System.out.println("unreachable"); */

The comment ends at the first star-slash, and the remaining text is parsed as Java, producing an error. The workaround is to replace the inner pair with line comments, or to delete rather than nest.

5) Comments Can Appear Anywhere Whitespace Can

int result = /* inline */ a + b;
System.out.println(/* separator */ label + value);

This compiles, and it is occasionally useful for annotating a confusing expression. Readability usually suffers, so use it sparingly.

6) Javadoc Tags Worth Knowing

@param names a parameter and should match the signature exactly. @return describes the returned value and is omitted from void methods. @throws documents a checked exception that may be thrown. @since marks the version an member appeared in. @see cross-references another class or method. @author and @version are conventional in headers. @deprecated flags a member that should no longer be used, and since Java 9 you also have @deprecatedForRemoval, which generates a removal warning for callers.

7) How javadoc Actually Produces Documentation

Run the tool against your source:

javadoc -d docs src/com/example/Calculator.java

You get HTML pages, an index, a search box, and cross-linked types. Modern builds run it through Maven or Gradle automatically, and the doclint tool checks your comments for errors such as a malformed tag or a @param for a parameter that does not exist. Enable it with -Xdoclint:all when you want to catch broken documentation in a build.

8) Comments and Performance

javac removes every comment before producing bytecode. A class with heavy documentation and the same class with no comments at all produce functionally identical bytecode. So commenting code out while debugging costs nothing at run time, but leaving dead commented code behind confuses the next person who reads the file.

9) When Not to Comment

Do not write a comment that restates the code. int count = 0; followed by // count is set to 0 tells a reader nothing. Comment the reason instead: // reset because the parser reuses this buffer between records. The useful signal is the intent the code cannot express, such as why an unusual constant was chosen or which bug a workaround is guarding against.

10) Comments the Compiler Never Sees

Two extra forms matter when writing tests or data files. Text blocks using triple double quotes, and // or /* */ inside a string literal, are just characters to the compiler. That also means a commented-out snippet containing a string with slashes can close a block comment early, which is another reason to delete dead code rather than keep it commented.

Runnable Code Example: Java Comments

Java 17+
Main.java
Run Online
import java.util.List;
import java.util.ArrayList;
/**
 * Demonstrates every comment syntax Java supports.
 *
 * <p>This block is a Javadoc comment because it opens with two stars.
 * The javadoc tool turns it into HTML.</p>
 *
 * @author Tanmoy
 * @since 1.0
 */public class CommentDemo {
    /** Timeout used by the retry logic, in seconds. */ private static final int TIMEOUT = 30;
    // A single-line comment sitting above a field.
    // Repeated lines are perfectly legal.
    /*
     * A multi-line comment. It runs until the first star-slash,
     * no matter how long it gets.
     */ private static final String label = "Calculator";
    /**
     * Adds two integers.
     *
     * @param a the first operand
     * @param b the second operand
     * @return the sum of a and b
     * @throws IllegalArgumentException if either operand is negative
     */ public static int add(int a, int b) {
        if (a < 0 || b < 0) {
            throw new IllegalArgumentException("operands must be non-negative");
        } return a + b;
        // trailing single-line comment
    } // 1) Block comments may sit inside an expression
    public static int combine(int a, int b) {
        return a /* left */ + /* operator */ b;
    } // 2) A comment inside a string is just text, not a comment
    public static String notAComment() {
        return "// this is not a comment /* neither is this */";
    } // 3) Text blocks hold characters that would otherwise be comments
    public static String textBlock() {
        return """
                // this line is part of the string
                block comment inside a text block: /* still text */
                """;
    } /*
     * 4) Block comments do NOT nest. This whole class compiles because
     * the inner pair below is written as line comments instead:
     */ public static void nestingDemo() {
        // int removed = 1;
        // /* also removed */ String name = "gone";
        System.out.println("nesting demo ran");
    } /**
     * Builds the list used by {@link #add(int, int)} style cross-references.
     *
     * @return a list holding the label
     * @deprecated use {@link #label()} instead
     */ @Deprecated public static List<String> buildList() {
        List<String> items = new ArrayList<>();
        items.add(label);
        return items;
    } public static String label() {
        return label;
    } public static void main(String[] args) {
        System.out.println("timeout=" + TIMEOUT);
        System.out.println("add(10,20)=" + add(10, 20));
        System.out.println("combine(10,20)=" + combine(10, 20));
        System.out.println("notAComment=" + notAComment());
        System.out.println("textBlock:");
        System.out.print(textBlock());
        nestingDemo();
        System.out.println("buildList=" + buildList());
        // 5) try-with-resources is safer than commenting code out
        try(java.io.BufferedReader r = new java.io.BufferedReader(new java.io.StringReader("data"))) {
            System.out.println("first line=" + r.readLine());
        } catch (java.io.IOException e) {
            // 6) catching and ignoring is only acceptable when nothing can be done
        }
    }
}// --- Expected console output ---
// timeout=30
// add(10,20)=30
// combine(10,20)=30
// notAComment=// this is not a comment /* neither is this */
// textBlock:
// // this line is part of the string
// block comment inside a text block: /* still text */
// nesting demo ran
// buildList=[Calculator]
// first line=data

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

What are the three comment types in Java and how do they differ?

Single-line (// to end of line) for one-line notes, block (/* */) for longer notes, and Javadoc (/** */) which the javadoc tool reads to generate HTML documentation.
Q2

Can block comments be nested?

No. The first star-slash closes the comment and everything after it is parsed as code, so nesting block comments fails to compile.
Q3

Do comments affect program performance?

No. javac strips every comment before producing bytecode, so a heavily commented class produces the same bytecode as an uncommented one.
Q4

Why is my Javadoc not appearing in the generated documentation?

Most often a blank line between the comment and the declaration, which detaches it from the member. It must sit immediately above the class, method, field, or constructor.
Q5

What does the javadoc tool actually do?

It parses /** */ comments, resolves @param, @return, @throws, and similar tags against the real signatures, and writes searchable HTML pages. Its doclint check reports malformed tags and parameters that do not exist.
Q6

Can you write a comment inside a string literal?

Yes, and the compiler treats it as ordinary text. That is also why a commented-out block containing a string literal can accidentally terminate a block comment early.
Q7

Is it good practice to comment out unused code instead of deleting it?

No. It has no runtime cost, since comments are stripped, but it leaves misleading code in the file and version control already preserves history. Commenting out is a short-lived debugging technique.
Q8

What is the difference between @Deprecated and @deprecatedForRemoval?

@deprecated marks a member as no longer recommended and generates a warning for callers. @deprecatedForRemoval, available since Java 9, additionally indicates it is scheduled for removal and is meant to be temporary.
Q9

Should I document private methods with Javadoc?

Generally no. Document public APIs thoroughly with Javadoc, since library users read it, and keep comments on private code short. Documenting everything produces noise that hides the parts that matter.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

1) Explain why, not what. A comment that restates the code is dead weight, while a comment recording the reason for an unusual constant or a bug workaround saves real time.
2) Use // for a single idea and reserve block comments for genuine multi-line explanations, not for disabling code.
3) Delete dead code rather than commenting it out; git already remembers it and the bytecode is identical either way.
4) Put a Javadoc comment on every public class and public method in a library, placed immediately above the declaration with no blank line between.
5) Keep @param names identical to the real parameter names so doclint can validate them.
6) Write the first sentence as a complete summary, because that is the line tools and IDEs show in tooltips.
7) Mark anything you are retiring with both @Deprecated and @Deprecated forRemoval so callers get a clear signal.
8) Avoid comments inside expressions and long trailing comment blocks; they drift out of date the moment the line below changes.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.