Skip to content

Java Code Comments

Comments are parts of a program that will not be executed by the compiler. They exist to explain the functionality, purpose, or complex logic of the code to human readers. Writing clear and well-organized comments is one of the important practices in professional software development. Java supports three types of comments.

1. Single-line Comment

Single-line comments start with double slashes // and continue until the end of that line. They are usually used to provide brief explanations for a single statement or a small piece of code.

Syntax:

java
// This is a single-line comment

Example:

java
int age = 30; // Declare and initialize a variable named age

// Call method to calculate sum
calculateSum();

2. Multi-line Comment

Multi-line comments start with /* and end with */. They can span multiple lines and are usually used to provide more detailed explanations or temporarily disable a large block of code.

Syntax:

java
/*
  This is a multi-line comment.
  It can contain any number of lines of text.
*/

Example:

java
/*
 * This is a method that calculates the sum of two integers.
 * Parameter a: First integer
 * Parameter b: Second integer
 * Return value: Sum of a and b
 */
public int add(int a, int b) {
    return a + b;
}

/*
  Temporarily disabling the following code block for testing
  String message = "Hello";
  System.out.println(message);
*/

Note: Multi-line comments cannot be nested. For example, /* ... /* ... */ ... */ is invalid.

3. Documentation Comment

Documentation comments are a special type of multi-line comment that starts with /** and ends with */. These comments can be extracted by the javadoc tool to automatically generate official API documentation for the program.

Documentation comments are the best way to provide professional, standardized descriptions for classes, interfaces, methods, and fields. They support using special @ tags to mark parameters, return values, exceptions, and other information.

Syntax:

java
/**
 * This is a documentation comment.
 * @tag description
 */

Common Javadoc Tags:

  • @param: Describes a method parameter.
  • @return: Describes the return value of a method.
  • @throws or @exception: Describes exceptions that a method may throw.
  • @author: Indicates the author.
  • @version: Indicates the version number.
  • @see: References other related classes or methods.
  • @deprecated: Marks a method or class as obsolete and not recommended for use.

Example:

java
/**
 * Represents a bank account, providing deposit and withdrawal functionality.
 * 
 * @author Cascade
 * @version 1.0
 */
public class BankAccount {

    private double balance;

    /**
     * Deposits money into the account.
     * The amount must be positive.
     * 
     * @param amount The amount to deposit, must be greater than 0.
     * @throws IllegalArgumentException if the deposit amount is non-positive.
     */
    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive");
        }
        this.balance += amount;
    }

    /**
     * Gets the current account balance.
     * 
     * @return The current balance of the account.
     */
    public double getBalance() {
        return this.balance;
    }
}

Why and When to Write Comments?

  • "Why" not "What": Good comments should explain the intent of the code (why it's done this way), not simply restate what the code itself does.

    • Bad comment: i++; // Increment i by 1 (this is obvious)
    • Good comment: i++; // Index needs to skip the header row (explains the reason)
  • Complex Logic: When you write complex algorithms or business logic, add comments to explain how they work.

  • Public APIs: All classes and methods exposed to other developers should have detailed documentation comments.

  • Code Maintenance: When you fix a bug or make a non-intuitive modification, leave a comment explaining why.

Remember, the code itself should be clear and self-explanatory. Comments are supplements, not remedies for poorly written code. Clean code with appropriate comments is the hallmark of high-quality software.

Content is for learning and research only.