Java Notes
Complete guide to Java comments — single-line, multi-line, and Javadoc comments with best practices, documentation tags, when to comment, and when not to.
Comments are non-executable text in your source code meant for human readers. The compiler completely ignores them. Java supports three types of comments, each with a specific purpose.
Three Types of Comments
1. Single-Line Comments (//)
Everything after // to the end of that line is a comment:
public class SingleLineComments {
public static void main(String[] args) {
// This is a single-line comment
int age = 25; // Inline comment: declaring age
// You can comment out code to disable it:
// System.out.println("This won't execute");
System.out.println("Age: " + age);
// Multiple single-line comments for longer explanations:
// Calculate the birth year based on current year
// and the person's age
int birthYear = 2024 - age;
System.out.println("Birth year: " + birthYear);
}
}Age: 25 Birth year: 1999
2. Multi-Line Comments (/* */)
Everything between /* and */ is a comment, spanning multiple lines:
public class MultiLineComments {
public static void main(String[] args) {
/* This is a multi-line comment.
It can span as many lines as needed.
Useful for longer explanations. */
/* You can also use it on a single line */
int result = /* inline comment in expression */ 5 + 3;
/*
* Common style: asterisk on each line
* (looks cleaner and organized)
* This explains the complex algorithm below.
*/
System.out.println("Result: " + result);
/* Commenting out a block of code:
int x = 10;
int y = 20;
System.out.println(x + y);
*/
}
}Result: 8
3. Javadoc Comments (/** */)
Special documentation comments processed by the javadoc tool to generate HTML documentation:
/**
* Represents a bank account with basic operations.
* <p>
* This class provides deposit, withdrawal, and balance
* inquiry functionality with overdraft protection.
* </p>
*
* @author WohoTech Team
* @version 2.0
* @since 1.0
* @see Transaction
*/
public class BankAccount {
private String accountHolder;
private double balance;
/**
* Creates a new bank account with the specified holder and initial balance.
*
* @param accountHolder the name of the account owner
* @param initialBalance the starting balance (must be non-negative)
* @throws IllegalArgumentException if initialBalance is negative
*/
public BankAccount(String accountHolder, double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException("Balance cannot be negative");
}
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
/**
* Deposits money into the account.
*
* @param amount the amount to deposit (must be positive)
* @return the new balance after deposit
* @throws IllegalArgumentException if amount is not positive
*/
public double deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balance += amount;
return balance;
}
/**
* Withdraws money from the account.
* <p>
* This method checks for sufficient funds before processing.
* </p>
*
* @param amount the amount to withdraw
* @return {@code true} if withdrawal was successful, {@code false} otherwise
*/
public boolean withdraw(double amount) {
if (amount > balance) {
return false;
}
balance -= amount;
return true;
}
/**
* Returns the current account balance.
*
* @return the current balance in dollars
*/
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 1000);
account.deposit(500);
account.withdraw(200);
System.out.println("Balance: $" + account.getBalance());
}
}Balance: $1300.0
Javadoc Tags Reference
| Tag | Purpose | Example |
|---|---|---|
@param | Method/constructor parameter | @param name the user's name |
@return | What the method returns | @return the calculated total |
@throws / @exception | Possible exceptions | @throws IOException if file not found |
@author | Class author | @author John Doe |
@version | Class version | @version 1.2.3 |
@since | When it was added | @since 2.0 |
@see | Cross-reference | @see ArrayList |
@deprecated | Mark as outdated | @deprecated Use newMethod() instead |
{@code text} | Inline code formatting | {@code null} |
{@link Class#method} | Clickable link | {@link String#length()} |
When to Comment (and When NOT To)
Good Comments
[1, 2, 5, 8, 9]
Bad Comments (Avoid These)
Comment Best Practices
- Write self-documenting code first — good names reduce the need for comments
- Comment WHY, not WHAT — code already shows what; explain the reasoning
- Keep comments up-to-date — outdated comments are worse than none
- Use Javadoc for public APIs — every public class and method should have Javadoc
- Don't comment out code — use version control (git) to track old code
- Use TODO/FIXME consistently — IDEs can find these for you
// BEFORE (needs comments because code is unclear):
// Check if user can access the resource
if (u.getR() >= 3 && u.getS() == 1 && !u.isB()) {
// grant access
}
// AFTER (self-documenting, no comments needed):
boolean hasRequiredRole = user.getRole() >= Role.ADMIN;
boolean isActiveSubscription = user.getSubscriptionStatus() == Status.ACTIVE;
boolean isNotBanned = !user.isBanned();
if (hasRequiredRole && isActiveSubscription && isNotBanned) {
grantAccess(user);
}Common Mistakes
- Leaving commented-out code — use Git/version control. Dead code clutters and confuses.
- Writing obvious comments —
i++; // increment iadds no value. Comment the WHY, not the WHAT. - Not updating comments when code changes — a comment that contradicts the code is actively harmful.
- Nesting multi-line comments —
/* outer /* inner */ */doesn't work. Multi-line comments don't nest. - Using comments instead of better code — if you need a comment to explain what code does, consider renaming variables or extracting methods.
Interview Questions
Q1: What are the three types of comments in Java?
Answer: (1) Single-line comments (//) — from // to end of line. (2) Multi-line comments (/* */) — everything between the markers, can span lines. (3) Javadoc comments (/** */) — special documentation comments processed by the javadoc tool to generate HTML API documentation.
Q2: Do comments affect program performance?
Answer: No. Comments are completely removed during compilation. They exist only in source code (.java files) and do not appear in bytecode (.class files). They have zero impact on runtime performance or file size of the compiled program.
Q3: What is Javadoc and what are common Javadoc tags?
Answer: Javadoc is a documentation generation tool that creates HTML API documentation from /** */ comments. Common tags: @param (parameter description), @return (return value), @throws (exception), @author (author name), @version (version number), @since (first version), @see (cross-reference), @deprecated (mark obsolete).
Q4: Can multi-line comments be nested in Java?
Answer: No. /* outer /* inner */ */ is invalid — the first */ ends the comment, and the remaining */ causes a compile error. To comment out code that already contains multi-line comments, use single-line comments (//) for each line.
Q5: When should you write comments?
Answer: Write comments when: (1) explaining WHY a design decision was made, (2) documenting public APIs (Javadoc), (3) marking TODOs/FIXMEs, (4) clarifying complex algorithms or regex patterns, (5) legal/copyright notices. Avoid comments that merely restate what code does — instead, write clearer code.
Summary
Comments are essential for documentation but should complement, not replace, well-written code. Use single-line comments for brief explanations, multi-line for disabling code blocks or longer notes, and Javadoc for public API documentation. The golden rule: comment why, not what — and always keep comments synchronized with the code they describe.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Comments in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, syntax, basics
Related Java Master Course Topics