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:
Code shows WHAT is happening. Comments explain WHY — the reasoning behind a decision that may not be obvious from the code itself.
In a team, others read your code. Clear comments reduce the time teammates spend understanding your logic and reduce review cycles.
Temporarily comment out a line or block to isolate a bug without deleting code. Uncomment to restore. Faster than Ctrl+Z.
Javadoc comments (/** */) are processed by the javadoc tool to generate professional HTML API documentation — exactly like the official Java API docs.
Code you write today will be maintained months or years later — possibly by you. Comments save hours of re-understanding your own logic.
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
// This entire line is a comment — compiler ignores it
int age = 21; // This is an inline comment — code runs, comment is ignoredSingle-Line Comment — Usage Examples
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
/* 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
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
/**
* 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
/**
* 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)
/** 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
Inline Tags
/**
* 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
# 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@paramand@returntags 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:
Comment Best Practices
Writing comments well is a skill. Here are the professional best practices followed in industry-grade Java codebases:
Code already shows what is happening. Comments should explain WHY — the business rule, the edge case, the reason for a non-obvious decision.
A good comment is concise. If you need a paragraph to explain a few lines of code, consider refactoring — cleaner code needs fewer comments.
Outdated comments are worse than no comments — they actively mislead readers. Always update the comment when you update the code.
Every public class, method, and field that others will use should have a Javadoc comment. This is a mandatory standard in professional teams.
Don't write: // increment i by 1 above i++; — this adds noise. Write comments for logic that isn't immediately obvious to another developer.
// TODO: add input validation and // FIXME: crashes when input is null are recognized by most IDEs and flag pending work clearly.
// ❌ 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:
/*
* 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.
/**
* 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.00Practice 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);
Easy2. Will this code compile? /* outer comment /* inner comment */ still outer? */ int x = 5;
Medium3. Which comment type would you use to document a public method in a library that other developers will use?
Easy4. What is the output? System.out.print("A"); /* System.out.print("B"); */ System.out.print("C");
Easy5. What Javadoc tags would you write for a method: public double divide(double a, double b) that throws ArithmeticException when b is 0?
Medium6. Can you use // inside a /* */ block comment? Does it have any effect?
Medium7. 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?
Medium8. What command generates Javadoc HTML for Student.java with author and version info, outputting to a folder named 'apidocs'?
HardSummary — 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:
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 →