☕ Java

Java Comments — Single-Line, Multi-Line & Javadoc

A complete beginner's guide to all three Java comment types — syntax, real-world usage, Javadoc tags, best practices, and how to generate professional HTML documentation using the javadoc tool.

📅

Last Updated

March 2026

⏱️

Read Time

10 min

🎯

Level

Beginner

Java Comments — Overview

In the previous chapter, we learned about Java Identifiers — the naming rules for variables, methods, classes, and packages. Now we will cover Java Comments — one of the most important but often overlooked habits of a professional developer.

A comment is a line or block of text in your source code that the Java compiler completely ignores. Comments are written for human readers — developers, teammates, or your future self — to explain what the code does, why a decision was made, or to temporarily disable code during debugging.

  • What you will learn: All three Java comment types (single-line, multi-line, Javadoc), complete Javadoc tag reference, how to generate HTML documentation, best practices, and common mistakes to avoid.

Why Use Comments in Java?

Good comments are a mark of a professional developer. Here is why comments matter in real-world Java development:

📖
Explain Intent

Code shows WHAT is happening. Comments explain WHY — the reasoning behind a decision that may not be obvious from the code itself.

🤝
Team Collaboration

In a team, others read your code. Clear comments reduce the time teammates spend understanding your logic and reduce review cycles.

🐛
Debugging Aid

Temporarily comment out a line or block to isolate a bug without deleting code. Uncomment to restore. Faster than Ctrl+Z.

📚
Auto-generate Docs

Javadoc comments (/** */) are processed by the javadoc tool to generate professional HTML API documentation — exactly like the official Java API docs.

🔮
Future Maintenance

Code you write today will be maintained months or years later — possibly by you. Comments save hours of re-understanding your own logic.

🎓
Learning Tool

Commenting each line as you learn forces you to understand what the code does. A great habit for beginners to build understanding.

  • ⚠️ Important: Java comments are completely removed by the compiler before bytecode is generated. They have zero impact on runtime performance — your .class file contains no trace of them.

Single-Line Comment ( // )

A single-line comment starts with two forward slashes //. Everything from // to the end of that line is ignored by the compiler. It is the most commonly used comment type in Java.

Syntax

☕ JavaSingle-Line Comment Syntax
// This entire line is a comment — compiler ignores it

int age = 21;   // This is an inline comment — code runs, comment is ignored

Single-Line Comment — Usage Examples

☕ JavaSingleLineCommentDemo.java
public class SingleLineCommentDemo {
    public static void main(String[] args) {

        // Step 1: Declare variables
        int price = 500;       // price in rupees
        int quantity = 3;       // number of items

        // Step 2: Calculate total
        int total = price * quantity;  // multiply price by quantity

        // Step 3: Display result
        System.out.println("Total: " + total);

        // System.out.println("Debug: " + price);  ← disabled for now
    }
}

Output

Total: 1500
  • Best for: Short inline explanations, labeling steps, temporarily disabling a single line of code.

  • ⚠️ Note: // only comments out to the end of that line. The next line is live code unless it also has //.

Multi-Line Comment ( /* ... */ )

A multi-line comment (also called a block comment) starts with /* and ends with */. Everything between these two delimiters is ignored — it can span any number of lines.

Syntax

☕ JavaMulti-Line Comment Syntax
/* This is a single-line block comment */

/*
 * This is a multi-line comment.
 * It can span as many lines as needed.
 * The leading * on each line is just a style convention — not required.
 */

Multi-Line Comment — Usage Examples

☕ JavaMultiLineCommentDemo.java
public class MultiLineCommentDemo {

    /*
     * This method calculates the area of a rectangle.
     * Formula : Area = length × breadth
     * Both values must be positive integers.
     */
    static int calculateArea(int length, int breadth) {
        return length * breadth;
    }

    public static void main(String[] args) {

        int area = calculateArea(10, 5);
        System.out.println("Area: " + area);

        /*
         * The following block is temporarily disabled during testing.
         * Uncomment when the database connection is ready.
         *
         * DatabaseManager db = new DatabaseManager();
         * db.connect();
         * db.saveRecord(area);
         */
    }
}

Output

Area: 50
  • Best for: Explaining a block of logic, describing a method before Javadoc, temporarily disabling multiple lines of code.

  • Cannot be nested: /* outer /* inner */ */ will cause a compile error. The compiler treats the first */ as the end of the entire comment. Use // to comment out code that already has block comments inside it.

Documentation Comment ( /** ... */ ) — Javadoc

A Javadoc comment starts with /** (double asterisk) and ends with */. It is a special kind of block comment designed to be processed by the javadoc tool, which auto-generates professional HTML API documentation — exactly like the official Java SE API documentation.

Javadoc comments are placed immediately before the class, method, or field they document. They support special Javadoc tags (starting with @) that structure the documentation.

Javadoc on a Class

☕ JavaJavadoc on Class
/**
 * Represents a student enrolled in a course.
 *
 * <p>This class stores the student's name, roll number, and GPA.
 * It provides methods to calculate grade and check pass/fail status.</p>
 *
 * @author  Tech Sustainify
 * @version 1.0
 * @since   2026-01-01
 */
public class Student {
    // class body
}

Javadoc on a Method

☕ JavaJavadoc on Method
/**
 * Calculates the sum of two integers.
 *
 * @param  a  the first integer operand
 * @param  b  the second integer operand
 * @return    the sum of {@code a} and {@code b}
 * @throws IllegalArgumentException if either value is negative
 */
public int add(int a, int b) {
    if (a < 0 || b < 0) {
        throw new IllegalArgumentException("Values must be non-negative");
    }
    return a + b;
}

Javadoc on a Field (Variable)

☕ JavaJavadoc on Field
/** The maximum number of students allowed per batch. */
public static final int MAX_STUDENTS = 60;

/**
 * The full name of the student.
 * Must not be null or empty.
 */
private String studentName;

Javadoc Tags — Complete Reference

Javadoc supports block tags (start with @ at the beginning of a line) and inline tags (used inside description text, wrapped in {@...}). Here is a complete reference of the most important ones:

Block Tags

TagUsed OnDescriptionExample
@param name descriptionMethods, ConstructorsDescribes a method parameter. One tag per parameter.@param age the age of the student
@return descriptionMethodsDescribes the return value. Omit for void methods.@return the sum of a and b
@throws ExceptionType descriptionMethods, ConstructorsDocuments an exception the method can throw. Also: @exception.@throws IOException if file not found
@author nameClasses, InterfacesNames the author of the class.@author Tech Sustainify
@version textClasses, InterfacesSpecifies the current version of the class.@version 2.1.0
@since textClasses, Methods, FieldsIndicates when this element was added.@since Java 8 / @since 2026-01-01
@deprecated descriptionClasses, Methods, FieldsMarks an element as outdated. IDEs show a strikethrough.@deprecated Use newMethod() instead
@see referenceClasses, Methods, FieldsAdds a 'See Also' reference link.@see java.util.ArrayList
@serial descriptionFieldsDocuments serializable fields.@serial the default serial version
@serialField name type descriptionClassesDocuments ObjectStreamField components.@serialField id int the student ID

Inline Tags

Inline TagDescriptionExample
{@code text}Renders text in code font without HTML processing. Preferred for inline code.Returns {@code null} if not found
{@link package.Class#member}Creates a clickable hyperlink to another documented element.See {@link java.util.Scanner}
{@linkplain package.Class#member}Same as @link but renders in plain text font instead of code font.See {@linkplain Student#getName}
{@value package.Class#field}Inserts the value of a static field constant inline.Default is {@value MAX_SIZE}
{@literal text}Renders text literally — HTML special chars like < > & are escaped.{@literal a < b}
{@inheritDoc}Copies the Javadoc from the nearest overridden / implemented method.{@inheritDoc}
☕ JavaJavadocTagsDemo.java — Comprehensive Example
/**
 * Manages a student's academic record.
 *
 * <p>Use {@link StudentManager} to create and manage multiple students.</p>
 *
 * @author  Tech Sustainify
 * @version 1.2
 * @since   2026-01-01
 */
public class Student {

    /** The maximum GPA on a 10-point scale. */
    public static final double MAX_GPA = 10.0;

    /** The full name of the student. */
    private String name;

    /** The student's GPA on a 10-point scale. */
    private double gpa;

    /**
     * Creates a new Student with the given name and GPA.
     *
     * @param name  the full name of the student; must not be {@code null}
     * @param gpa   the student's GPA; must be between 0.0 and {@value MAX_GPA}
     * @throws IllegalArgumentException if name is null or GPA is out of range
     */
    public Student(String name, double gpa) {
        if (name == null) throw new IllegalArgumentException("Name must not be null");
        if (gpa < 0 || gpa > MAX_GPA) throw new IllegalArgumentException("GPA out of range");
        this.name = name;
        this.gpa  = gpa;
    }

    /**
     * Returns the student's letter grade based on GPA.
     *
     * <ul>
     *   <li>9.0 – 10.0 → {@code 'O'} (Outstanding)</li>
     *   <li>7.5 – 8.9  → {@code 'A'}</li>
     *   <li>6.0 – 7.4  → {@code 'B'}</li>
     *   <li>Below 6.0  → {@code 'F'} (Fail)</li>
     * </ul>
     *
     * @return  the letter grade as a {@code char}
     * @since   1.1
     */
    public char getGrade() {
        if      (gpa >= 9.0) return 'O';
        else if (gpa >= 7.5) return 'A';
        else if (gpa >= 6.0) return 'B';
        else                 return 'F';
    }

    /**
     * @deprecated Use {@link #getGrade()} instead. This method will be
     *             removed in version 2.0.
     * @return grade as a String
     */
    @Deprecated
    public String getGradeOld() {
        return String.valueOf(getGrade());
    }
}

Generating HTML Docs with the javadoc Tool

The javadoc command-line tool reads your /** */ comments and generates a complete, professional-looking HTML documentation website — exactly like the official Java SE 21 API docs. It is included in the JDK — no extra installation needed.

Basic javadoc Commands

CommandWhat it does
javadoc Student.javaGenerates docs for a single file in the current directory
javadoc *.javaGenerates docs for all .java files in current directory
javadoc -d docs Student.javaOutputs the HTML files into a folder named 'docs'
javadoc -d docs -author -version Student.javaIncludes @author and @version in the output
javadoc -d docs com.techsustainify.appGenerates docs for an entire package
javadoc -private -d docs Student.javaIncludes private members in the docs (by default only public/protected)
☕ TerminalStep-by-Step: Generate Javadoc HTML
# Step 1 — Navigate to your source folder
cd /path/to/your/project/src

# Step 2 — Generate docs into a 'docs' folder
javadoc -d docs -author -version Student.java

# Step 3 — Open the generated documentation
# On Windows:
start docs/index.html

# On macOS:
open docs/index.html

# On Linux:
xdg-open docs/index.html
  • 💡 Tip: Most IDEs (IntelliJ IDEA, Eclipse, VS Code) have built-in Javadoc generation — right-click your class → Generate Javadoc. No terminal needed.

  • 💡 Tip: In IntelliJ IDEA, type /** above a method and press Enter — it auto-generates the Javadoc skeleton with all @param and @return tags filled in.

Comparison — All Three Comment Types

Here is a quick side-by-side reference of all three Java comment types so you know exactly when to use each one:

FeatureSingle-Line ( // )Multi-Line ( /* */ )Javadoc ( /** */ )
Syntax start///*/**
Syntax endEnd of line*/*/
Spans multiple lines?NoYesYes
Processed by javadoc?NoNoYes
Supports @ tags?NoNoYes
Can be nested?Yes (stacked //)No — compile errorNo — compile error
Appears in .class?NoNoNo
IDE tooltip shows it?NoNoYes — hover docs
Best used forInline notes, disabling single linesExplaining blocks, disabling multiple linesDocumenting public classes, methods, fields

Comment Best Practices

Writing comments well is a skill. Here are the professional best practices followed in industry-grade Java codebases:

Comment WHY, not WHAT

Code already shows what is happening. Comments should explain WHY — the business rule, the edge case, the reason for a non-obvious decision.

📏
Keep Comments Short

A good comment is concise. If you need a paragraph to explain a few lines of code, consider refactoring — cleaner code needs fewer comments.

🔄
Keep Comments Updated

Outdated comments are worse than no comments — they actively mislead readers. Always update the comment when you update the code.

📋
Javadoc All Public APIs

Every public class, method, and field that others will use should have a Javadoc comment. This is a mandatory standard in professional teams.

🚫
Avoid Obvious Comments

Don't write: // increment i by 1 above i++; — this adds noise. Write comments for logic that isn't immediately obvious to another developer.

🔧
Use TODO and FIXME

// TODO: add input validation and // FIXME: crashes when input is null are recognized by most IDEs and flag pending work clearly.

☕ JavaGood vs Bad Comments
// ❌ BAD — states the obvious, adds no value
int age = 21;  // set age to 21

// ✅ GOOD — explains non-obvious business rule
int age = 21;  // minimum age to open a bank account per RBI guidelines


// ❌ BAD — cryptic without explanation
if (x > 86400) { reset(); }

// ✅ GOOD — explains the magic number
// 86400 = seconds in a day; reset session after 24 hours
if (x > 86400) { reset(); }


// ✅ GOOD — TODO for pending work
// TODO: replace this linear search with binary search for large datasets
for (int i = 0; i < arr.length; i++) { ... }

// ✅ GOOD — FIXME for known bugs
// FIXME: throws NullPointerException when user is not logged in
String username = user.getName();

Common Comment Mistakes to Avoid

Even experienced developers make comment mistakes. Here are the most common pitfalls and how to avoid them:

MistakeExampleWhy it's WrongFix
Nested block comments/* /* inner */ */The first */ ends the outer comment — compile errorUse // to comment out code containing /* */
Outdated comments// returns user age (code now returns username)Misleads every developer who reads itUpdate the comment whenever you change the code
Commented-out dead code left permanently// int x = oldCalc();Clutters the codebase — unclear if it's neededDelete it; use Git history to recover if needed
Javadoc on private members without purpose/** x */ private int x;Private fields rarely need Javadoc — adds noiseReserve Javadoc for public APIs; use // for private notes
Missing @param or @return in Javadoc/** Adds two numbers. */ public int add(int a, int b)Users of your API don't know what a and b meanAlways document each @param and @return
Mixing // inside /* *//* code // still commented */The // has no effect inside /* */; entire block is commentedUnderstand that // is irrelevant inside /* */
☕ JavaNested Comment Mistake — Compile Error
/*
 * Attempting to comment out a block that contains another block comment:
 *
 * int x = calculate(); /* uses old formula */
 *                                           ↑
 * Java sees THIS as the end of the outer /* comment
 * Everything after this is treated as live code → compile error!
 */

// ✅ Correct way to comment out code that has /* */ inside:
// int x = calculate(); /* uses old formula */

Complete Java Program — All Comment Types Together

Let us write one complete, professional Java program that demonstrates all three comment types used in the right context — exactly as you would write them in a real-world project.

☕ JavaBankAccount.java
/**
 * Represents a simple bank account with deposit and withdrawal operations.
 *
 * <p>This class demonstrates all three Java comment types in a real-world context.</p>
 *
 * @author  Tech Sustainify
 * @version 1.0
 * @since   2026-01-01
 */
public class BankAccount {

    /** Minimum balance required to keep the account active (in rupees). */
    public static final int MIN_BALANCE = 500;

    /** The current balance of the account. */
    private double balance;

    /** The name of the account holder. */
    private String holderName;

    /**
     * Creates a new BankAccount with an initial deposit.
     *
     * @param holderName    the name of the account holder; must not be null
     * @param initialAmount the opening balance; must be >= {@value MIN_BALANCE}
     * @throws IllegalArgumentException if initial amount is below minimum balance
     */
    public BankAccount(String holderName, double initialAmount) {
        // Validate the initial deposit before setting
        if (initialAmount < MIN_BALANCE) {
            throw new IllegalArgumentException(
                "Opening balance must be at least ₹" + MIN_BALANCE
            );
        }
        this.holderName = holderName;
        this.balance    = initialAmount;
    }

    /**
     * Deposits the given amount into the account.
     *
     * @param  amount  the amount to deposit; must be positive
     * @return         the updated balance after deposit
     * @throws IllegalArgumentException if amount is zero or negative
     */
    public double deposit(double amount) {
        /*
         * Business rule: deposits must be positive.
         * A zero deposit is meaningless and negative would be equivalent
         * to a withdrawal — which has its own method.
         */
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive");
        }
        balance += amount;
        return balance;  // return updated balance for confirmation
    }

    /**
     * Withdraws the given amount from the account.
     *
     * @param  amount  the amount to withdraw; must be positive
     * @return         the updated balance after withdrawal
     * @throws IllegalArgumentException if amount exceeds available balance
     */
    public double withdraw(double amount) {
        // Ensure withdrawal does not drop below minimum balance
        if (balance - amount < MIN_BALANCE) {
            throw new IllegalArgumentException(
                "Insufficient funds. Minimum balance of ₹" + MIN_BALANCE + " required."
            );
        }
        balance -= amount;
        return balance;
    }

    /**
     * Returns a formatted account summary string.
     *
     * @return account summary with holder name and current balance
     */
    public String getSummary() {
        return String.format("Account Holder: %s | Balance: ₹%.2f", holderName, balance);
    }

    public static void main(String[] args) {

        // Create a new account with ₹10,000 opening balance
        BankAccount account = new BankAccount("Rahul Sharma", 10000);

        // Perform transactions
        account.deposit(5000);    // add ₹5,000
        account.withdraw(3000);   // remove ₹3,000

        /*
         * TODO: integrate with the SMS notification service
         * to send transaction alerts after each deposit/withdrawal.
         */

        // Print the final account summary
        System.out.println(account.getSummary());
    }
}

Output

Account Holder: Rahul Sharma | Balance: ₹12000.00

Practice This Code — Live Editor

Java Comments — Interview Questions

These are commonly asked Java interview questions related to comments — from basic syntax to tricky edge cases and Javadoc usage.

Practice Questions — Test Your Knowledge

Test your understanding of Java Comments. Answer each question yourself before revealing the answer.

1. What is the output of this program? int x = 5; // x = 10; System.out.println(x);

Easy

2. Will this code compile? /* outer comment /* inner comment */ still outer? */ int x = 5;

Medium

3. Which comment type would you use to document a public method in a library that other developers will use?

Easy

4. What is the output? System.out.print("A"); /* System.out.print("B"); */ System.out.print("C");

Easy

5. What Javadoc tags would you write for a method: public double divide(double a, double b) that throws ArithmeticException when b is 0?

Medium

6. Can you use // inside a /* */ block comment? Does it have any effect?

Medium

7. You have a Java file with 500 lines and need to temporarily disable lines 200–250 for testing. What comment type would you use and why?

Medium

8. What command generates Javadoc HTML for Student.java with author and version info, outputting to a folder named 'apidocs'?

Hard

Summary — What You Learned in Java Comments

You have now mastered all three Java comment types and the professional practices around them. Here is a quick recap of everything covered in this chapter:

TopicKey Takeaway
What is a comment?Text ignored by the compiler — written for human readers, has zero performance impact
Single-line ( // )Starts with // — comments to end of line. Best for short inline notes and disabling one line
Multi-line ( /* */ )Wraps a block — starts /* ends */. Cannot be nested. Best for block explanations
Javadoc ( /** */ )Starts with ** — processed by javadoc tool to generate HTML docs. Supports @ tags
Key Javadoc block tags@param, @return, @throws, @author, @version, @since, @deprecated, @see
Key Javadoc inline tags{@code}, {@link}, {@linkplain}, {@value}, {@literal}, {@inheritDoc}
javadoc tooljavadoc -d docs -author -version FileName.java — generates HTML documentation
Best practiceComment WHY not WHAT. Keep comments short, accurate, and updated with code changes
Common mistakeNesting /* */ comments — causes compile error. Use // to comment out code with /* */ inside
Dead codeDo not leave commented-out code permanently — delete it and rely on Git history

The next step is understanding Java Data Types — primitive types (byte, short, int, long, float, double, char, boolean) and non-primitive types (String, Arrays, Classes) — which define what kind of data your variables can hold. Continue to the next chapter: Java Data Types →

Frequently Asked Questions (FAQ) — Java Comments