Java Comments

A comment in Java is text in your source code that the compiler completely ignores. Comments exist purely for humans: they explain what code does, why it does it, or temporarily disable code you’re not ready to delete. Mastering comments — including the often-overlooked Javadoc style — is a small skill with a big payoff, because well-commented code is easier to maintain, debug, and hand off to other developers (including your future self).

Overview: How Comments Work

Java source code is turned into bytecode by the compiler (javac) in a step called lexical analysis (tokenizing), which happens before the compiler even tries to understand your program’s structure. During tokenizing, the compiler scans the raw characters of your .java file and strips out anything it recognizes as a comment before any other processing occurs. This means comments never reach the parser, are never checked for syntax, are never compiled into bytecode, and add zero bytes to your final .class file or runtime performance cost. You could write a million lines of comments and the compiled program would run exactly as fast as one with none.

Java supports three comment forms:

  • Single-line comments (//) — everything from // to the end of that physical line is ignored.
  • Multi-line (block) comments (/* ... */) — everything between the opening /* and the first matching */ is ignored, even across multiple lines.
  • Javadoc comments (/** ... */) — a special block comment that tools like the javadoc generator read to produce HTML API documentation, and that IDEs read to show tooltips.

Because comment stripping happens before parsing, a comment can appear almost anywhere whitespace is allowed: between statements, inside expressions, even in the middle of a long method signature. The one thing comments cannot do is nest inside another block comment of the same kind, which is a common source of confusing compiler errors (covered below).

Syntax

Form Syntax Scope
Single-line // comment text From // to end of line
Multi-line /* comment text */ Everything between the delimiters, any number of lines
Javadoc /** comment text */ Placed directly above a class, field, or method it documents

Javadoc comments also support special tags that the documentation generator recognizes, the most common being:

  • @param name description — documents a method parameter
  • @return description — documents the return value
  • @throws ExceptionType description — documents an exception the method may throw
  • @author name and @since version — metadata about the code

Examples

Example 1: Single-line and multi-line comments together

public class Main {
    public static void main(String[] args) {
        // This program calculates the area of a rectangle
        int width = 5;
        int height = 10;

        /* Calculate the area
           by multiplying width and height */
        int area = width * height;

        System.out.println("Area: " + area); // print the result
    }
}

Output:

Area: 50

Here the single-line comment on the first line documents the whole program’s purpose, the block comment spans two lines to explain the calculation, and a trailing single-line comment annotates the final statement. The compiler removes all three before compiling; only the four executable statements remain.

Example 2: Javadoc comments on a class and method

/**
 * The Main class demonstrates the use of Javadoc comments.
 * Javadoc comments can be used to generate HTML documentation
 * with the javadoc command-line tool.
 */
public class Main {

    /**
     * Calculates the square of a given number.
     *
     * @param number the number to square
     * @return the square of the number
     */
    static int square(int number) {
        return number * number;
    }

    public static void main(String[] args) {
        int result = square(6);
        System.out.println("Square: " + result);
    }
}

Output:

Square: 36

The /** ... */ comments above the class and the square method are ordinary comments as far as javac is concerned — they don’t affect the output at all. Their real value shows up if you run the javadoc tool on this file: it reads the tags (@param, @return) and generates browsable HTML reference documentation, the same style used for Java’s own standard library docs.

Example 3: A realistic example — documenting logic and disabling debug code

public class Main {
    public static void main(String[] args) {
        // Convert Celsius to Fahrenheit
        double celsius = 25.0;

        // Formula: F = C * 9/5 + 32
        double fahrenheit = celsius * 9 / 5 + 32;

        /*
         * Uncomment the line below during debugging to see
         * the raw, unformatted result.
         */
        // System.out.println("Raw: " + fahrenheit);

        System.out.printf("%.1f Celsius is %.1f Fahrenheit%n", celsius, fahrenheit);
    }
}

Output:

25.0 Celsius is 77.0 Fahrenheit

This mirrors how comments are used in real projects: a short note explaining the formula, and a line of code that’s temporarily disabled by turning it into a comment (a technique called commenting out) rather than deleting it, so it can be restored quickly while debugging.

Under the Hood: What the Compiler Actually Does

  1. The compiler reads your .java file character by character during tokenizing.
  2. When it sees //, it discards every character until the next line break.
  3. When it sees /*, it discards every character until the first occurrence of */ — it does not track nested /* sequences.
  4. A /** ... */ comment is tokenized identically to /* ... */ by javac; the extra asterisk only matters to the separate javadoc tool, which re-reads the source and treats /** ... */ blocks specially when generating docs.
  5. After stripping, the remaining tokens (keywords, identifiers, operators, literals) are what the parser and compiler actually work with — comments never reach bytecode.

Common Mistakes

Mistake 1: Trying to nest block comments

Block comments do not nest. The compiler closes the comment at the first */ it finds, so code after that point is treated as active source — often producing confusing syntax errors far from the real problem.

/*
 * Outer comment starts here
 /* attempting a nested comment */
 * This text is now outside the comment and breaks compilation
 */

The fix is to never place /* inside another block comment. Use single-line // comments for the inner notes instead:

public class Main {
    public static void main(String[] args) {
        /*
         * Outer comment starts here.
         * Note: nested comment avoided; using // instead below.
         */
        // int debugValue = 42;
        System.out.println("Done");
    }
}

Output:

Done

Mistake 2: Forgetting to close a block comment

If you open a /* and forget the closing */, every line after it — including real code and closing braces — is silently swallowed into the comment, usually causing an “unclosed comment” or “reached end of file while parsing” error.

public class Main {
    public static void main(String[] args) {
        /* TODO: revisit this calculation
        int x = 5;
        System.out.println(x);
    }
}

This fails to compile because the block comment never ends, so the closing braces of main and Main are consumed as comment text. Always close every block comment you open:

public class Main {
    public static void main(String[] args) {
        /* TODO: revisit this calculation */
        int x = 5;
        System.out.println(x);
    }
}

Output:

5

Best Practices

  • Comment the why, not the what — good identifiers already show what code does; comments should explain reasoning, trade-offs, or non-obvious constraints.
  • Keep comments up to date. A comment that contradicts the code below it is worse than no comment at all, since it actively misleads readers.
  • Use Javadoc (/** ... */) on public classes, fields, and methods so IDEs can show hover documentation and so the javadoc tool can generate a reference site.
  • Avoid leaving large blocks of commented-out code in committed source files; version control already remembers deleted code, so delete it instead of hoarding it as comments.
  • Don’t over-comment trivial lines like i++; // increment i — it adds noise without adding understanding.
  • Use // for short, situational notes and /* */ for longer explanatory blocks that span several lines.

Practice Exercises

  • Write a program that declares two integer variables and prints their sum. Add a single-line comment above the declaration explaining what the variables represent, and a Javadoc-style comment above the main method describing the program’s purpose.
  • Take a working program that prints the factorial of a number, and comment out the line that prints the result using a block comment, replacing it with a line that prints “Calculation skipped” instead. Verify the program still compiles and runs.
  • Intentionally write a block comment that forgets its closing */ in a small test file, try to compile it with javac, and read the exact error message your compiler produces. Then fix it and confirm it compiles cleanly.

Summary

  • Comments are removed by the compiler during tokenizing and have zero effect on runtime behavior or performance.
  • // comments run to the end of the current line; /* */ comments can span multiple lines.
  • /** */ Javadoc comments are read by the javadoc tool and IDEs to generate and display documentation, using tags like @param and @return.
  • Block comments do not nest — the first */ closes the comment, which can silently break code that follows.
  • Forgetting to close a block comment swallows subsequent code, typically causing a compile error at the end of the file.
  • Write comments that explain reasoning and intent, keep them accurate, and avoid leaving stale commented-out code in your files.