Java Comments

Comments are an important part of Java programming. They allow developers to add notes, explanations, descriptions, and documentation directly inside source code.

Comments are written for humans, not for the Java Virtual Machine (JVM). When Java source code is compiled, comments are ignored by the compiler and do not become executable Java bytecode.

For example:

// This is a comment
int age = 25;

The Java compiler uses the int age = 25; statement but does not execute the comment.

Comments are especially useful when programs become large or when multiple developers work on the same project. Well-written comments can explain why a particular piece of code exists, describe complex logic, and provide useful documentation for classes and methods.

Java provides three commonly used forms of comments:

  • Single-line comments
  • Multi-line comments
  • Documentation comments

Why Are Comments Used in Java?

Comments can make source code easier to understand and maintain. A developer may understand their own code when writing it, but after several months, some parts of the program may no longer be obvious.

For example:

int total = price * quantity;

The code is simple enough to understand. But sometimes the reason behind a particular calculation may not be obvious.

A comment can explain the purpose:

// Calculate the total price before applying the discount
int total = price * quantity;

Comments can also be useful for:

  • Explaining complex logic
  • Describing the purpose of a method
  • Explaining important business rules
  • Temporarily disabling code during development
  • Providing information about classes and APIs
  • Helping other developers understand a project
  • Generating technical documentation

However, comments should not be used unnecessarily. Good code should be reasonably clear by itself, while comments should provide additional useful context.

What Is a Comment in Java?

A comment is text written inside Java source code that is ignored during normal compilation.

For example:

// This line is ignored by the compiler
System.out.println("Hello Java");

The comment explains the code, while the System.out.println() statement is executed.

Java supports three main comment styles:

// Single-line comment

/*
   Multi-line comment
*/

/**
 * Documentation comment
 */

Each type has a different purpose.

Single-Line Comments

A single-line comment is used when you want to write a comment on one line.

It begins with two forward slashes:

//

Everything after // on that line is treated as a comment.

For example:

// This is a single-line comment

You can also place a comment after Java code:

int age = 25; // Store the user's age

The Java compiler ignores everything after // on that line.

Basic Example of a Single-Line Comment

class Demo {

    public static void main(String[] args) {

        // Store the user's age
        int age = 25;

        System.out.println(age);
    }
}

The comment:

// Store the user's age

does not affect program execution.

Multiple Single-Line Comments

You can use several single-line comments in a program:

// Create the first number
int a = 10;

// Create the second number
int b = 20;

// Calculate the sum
int sum = a + b;

// Display the result
System.out.println(sum);

Each comment begins with //.

Commenting Code Temporarily

Single-line comments can also be used to temporarily disable a line of code.

For example:

int a = 10;
// int b = 20;

System.out.println(a);

The declaration of b is commented out, so Java does not compile it as executable code.

This technique is sometimes useful during debugging and development.

However, large amounts of commented-out old code should generally be removed rather than kept indefinitely. Version-control systems such as Git can preserve previous versions of the code.

Single-Line Comment After Code

A comment does not have to appear on a separate line.

For example:

int age = 25; // User's age

Everything after // is treated as a comment.

Another example:

int salary = 50000; // Monthly salary

This style can be useful for short explanations.

When Should You Use Single-Line Comments?

Single-line comments are useful for short explanations.

For example:

// Check whether the user is eligible
if (age >= 18) {
    System.out.println("Eligible");
}

They are also useful for explaining individual variables or small pieces of logic:

int maxAttempts = 3; // Maximum login attempts

Avoid writing comments that simply repeat what the code already clearly says.

For example:

// Add 1 to count
count++;

The code is already obvious. A comment like this usually provides little additional value.

Multi-Line Comments

A multi-line comment is used when a comment needs to span multiple lines.

It begins with:

/*

and ends with:

*/

Everything between these symbols is treated as a comment.

For example:

/*
This is a multi-line comment.
It can contain multiple lines.
Java ignores this text during compilation.
*/

Multi-Line Comment Example

class Demo {

    public static void main(String[] args) {

        /*
         * Calculate the total price.
         * The total is calculated by
         * multiplying price by quantity.
         */

        int price = 100;
        int quantity = 5;

        int total = price * quantity;

        System.out.println(total);
    }
}

The entire section between /* and */ is ignored by the compiler.

Multi-Line Comments on One Line

Although multi-line comments are designed for multiple lines, they can also be written on a single line:

/* This is a comment */

This is valid Java.

However, for a short comment, a single-line comment is often more readable:

// This is a comment

Multi-Line Comments for Explanations

Multi-line comments are useful when explaining a complex section of code.

For example:

/*
 * The application first validates the user's credentials.
 * If the credentials are correct, the user is allowed
 * to continue to the dashboard.
 */
validateUser();

This provides more context than a short single-line comment.

Multi-Line Comments and Code

You can temporarily comment out multiple lines of code:

/*
int a = 10;
int b = 20;
int sum = a + b;

System.out.println(sum);
*/

Java will treat all of it as a comment.

This can be useful while testing or debugging.

However, as with single-line commented-out code, it is better not to leave obsolete code commented out permanently.

Documentation Comments

Documentation comments are a special type of comment used to describe Java classes, methods, constructors, fields, and other program elements.

They begin with:

/**

and end with:

*/

The important difference is the double asterisk after the opening slash:

/**

Documentation comments are commonly called Javadoc comments because they are used by the Java javadoc tool to generate HTML documentation.

Basic Documentation Comment

/**
 * Represents a student in the application.
 */
class Student {
}

The comment describes the purpose of the Student class.

Documentation Comments for Methods

You can document a method like this:

/**
 * Adds two numbers and returns the result.
 */
static int add(int a, int b) {
    return a + b;
}

The documentation explains what the method does.

Documentation comments become especially useful in libraries and APIs where developers need to understand how classes and methods should be used.

Javadoc Tags

Documentation comments can contain special tags beginning with @.

Some commonly used Javadoc tags include:

@author
@param
@return
@throws
@see
@since
@deprecated

These tags provide structured information about program elements.

The @param Tag

The @param tag describes a method parameter.

For example:

/**
 * Calculates the total price.
 *
 * @param price the price of one item
 * @param quantity the number of items
 */
static double calculateTotal(double price, int quantity) {
    return price * quantity;
}

Here, the documentation explains both parameters.

The @return Tag

The @return tag describes the value returned by a method.

/**
 * Adds two numbers.
 *
 * @param a first number
 * @param b second number
 * @return the sum of the two numbers
 */
static int add(int a, int b) {
    return a + b;
}

This tells developers what the method returns.

The @throws Tag

The @throws tag documents an exception that a method may throw.

For example:

/**
 * Finds a student by ID.
 *
 * @param id student ID
 * @return the matching student
 * @throws IllegalArgumentException if the ID is invalid
 */
static Student findStudent(int id) {
    // Method implementation
    return null;
}

The documentation tells users of the method about the possible exception.

The @author Tag

The @author tag can identify the author of a class or other documented element.

/**
 * Represents a customer account.
 *
 * @author Development Team
 */
class Customer {
}

In modern software projects, teams may prefer to manage authorship through version-control systems such as Git rather than relying heavily on @author.

The @since Tag

The @since tag indicates the version in which an API element was introduced.

/**
 * Provides customer information.
 *
 * @since 2.0
 */
class CustomerInfo {
}

This can be particularly useful when maintaining libraries across multiple versions.

The @deprecated Tag

The @deprecated tag indicates that an API element should generally no longer be used.

For example:

/**
 * Old calculation method.
 *
 * @deprecated Use calculateTotal() instead.
 */
@Deprecated
static int oldCalculation(int a, int b) {
    return a + b;
}

The @Deprecated annotation is used by Java to formally mark the program element as deprecated, while the Javadoc tag explains the situation in generated documentation.

Complete Javadoc Example

Here is a complete example:

/**
 * Provides basic mathematical operations.
 */
class Calculator {

    /**
     * Adds two integers.
     *
     * @param a first number
     * @param b second number
     * @return the sum of a and b
     */
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {

        int result = add(10, 20);

        System.out.println(result);
    }
}

The class and method have documentation comments that explain their purpose.

Difference Between Single-Line, Multi-Line, and Documentation Comments

The three comment styles have different purposes.

Comment TypeSyntaxMain Purpose
Single-line//Short comments
Multi-line/* ... */Longer comments spanning multiple lines
Documentation/** ... */API and program-element documentation

The most important difference between multi-line and documentation comments is the opening syntax.

Multi-line:

/*

Documentation:

/**

The extra * makes the second one a documentation comment.

Comments and Compilation

Consider this program:

// Display a message
class Demo {

    public static void main(String[] args) {

        /*
         * Print a greeting.
         */

        System.out.println("Hello Java!");
    }
}

When the Java compiler processes this source code, the comments are not treated as executable statements.

Conceptually, the compiler is concerned with the actual Java program structure, such as:

class Demo {

    public static void main(String[] args) {

        System.out.println("Hello Java!");
    }
}

Comments do not produce normal executable instructions for the JVM.

Comments Do Not Change Program Output

Adding a comment normally does not change what the program does.

For example:

class Demo {

    public static void main(String[] args) {

        int a = 10;
        int b = 20;

        System.out.println(a + b);
    }
}

and:

class Demo {

    public static void main(String[] args) {

        // Store the first number
        int a = 10;

        // Store the second number
        int b = 20;

        // Display the sum
        System.out.println(a + b);
    }
}

Both programs produce:

30

The comments only provide additional information for people reading the source code.

Comments Are Not Completely Free

Although comments do not become executable instructions in the same way as Java code, they are still part of the source file. Extremely large amounts of unnecessary comments can make source code harder to read and can increase source-file size.

The goal is not to write as many comments as possible. The goal is to write useful comments.

Good comments explain information that is not immediately obvious from the code.

Good Comments vs Bad Comments

Consider this:

// Increment count by one
count++;

This comment simply repeats the code.

A more useful comment might explain why:

// Count this attempt so the application can enforce the retry limit.
count++;

The second comment provides additional context.

Another example:

// Use UTC because transaction timestamps are stored in the database in UTC.
LocalDateTime timestamp = LocalDateTime.now(ZoneOffset.UTC);

This explains the reasoning behind the code.

Comments Should Explain Why When Appropriate

One of the most useful principles of commenting is:

Code usually explains what it does; comments can explain why it does it.

For example:

// Use three retries to handle temporary network failures.
int maxRetries = 3;

The code tells us the value is 3. The comment explains the reason for the value.

This kind of comment can be valuable to future developers.

Commenting Best Practices

Good commenting practices include:

Keep Comments Clear

Write comments that are easy to understand.

// Check whether the account is active
if (account.isActive()) {
    ...
}

Keep Comments Relevant

A comment should describe code that is still present and accurate.

Outdated comments can be more confusing than having no comment.

Avoid Obvious Comments

Avoid comments that simply repeat the code.

// Set age to 25
int age = 25;

The code already explains this.

Explain Complex Logic

When code involves complicated calculations or unusual business rules, a useful comment can provide important context.

Update Comments When Code Changes

If the code changes, review related comments as well.

An incorrect comment can lead developers to misunderstand the program.

Prefer Clear Code

Do not use comments as a replacement for readable code.

For example, instead of:

int x = 86400; // Number of seconds in one day

you could make the code more descriptive:

int secondsPerDay = 86400;

A clear variable name reduces the need for a comment.

Comments in a Java Program

Here is a program demonstrating all three types of comments:

/**
 * Demonstrates different types of Java comments.
 */
class CommentDemo {

    public static void main(String[] args) {

        // Store the first number
        int a = 10;

        /*
         * Store the second number.
         * This value is used to calculate the total.
         */
        int b = 20;

        int sum = a + b;

        System.out.println(sum);
    }
}

This example contains:

  • A documentation comment before the class
  • A single-line comment before a
  • A multi-line comment before b
  • Normal Java statements

Comments and IDE Shortcuts

Most Java IDEs provide keyboard shortcuts for adding and removing comments.

For example, IntelliJ IDEA, Eclipse, and VS Code commonly support shortcuts for toggling line comments and block comments.

The exact shortcut can vary depending on the operating system and editor configuration, so developers should check the documentation or keyboard-shortcut settings of their IDE.

Comments vs Documentation

It is useful to understand the difference between ordinary comments and documentation comments.

Ordinary comment:

// Calculate the total

This is primarily a note for developers reading the source code.

Documentation comment:

/**
 * Calculates the total price.
 *
 * @param price item price
 * @param quantity number of items
 * @return total price
 */

This is structured documentation that can be processed by the Javadoc tool.

Generating Documentation With Javadoc

Java includes a documentation-generation tool called javadoc.

If a project contains documentation comments, the javadoc tool can process them and generate documentation, commonly in HTML format.

For example:

/**
 * Represents a product.
 */
public class Product {

    /**
     * Returns the product price.
     *
     * @return product price
     */
    public double getPrice() {
        return 100.0;
    }
}

A Javadoc tool can use these comments to generate API documentation for developers.

This is one of the major differences between ordinary comments and documentation comments.

Important Difference Between /* */ and /** */

These two styles look very similar:

/*
 * Normal multi-line comment
 */

and:

/**
 * Documentation comment
 */

The first is an ordinary multi-line comment.

The second is a documentation comment intended for tools such as Javadoc.

The extra * after the slash is important:

/*  → multi-line comment

/** → documentation comment

Frequently Asked Questions

What are comments in Java?

Comments are explanatory text written inside Java source code. They are intended for developers and are not executed as normal program instructions.

How many types of comments does Java have?

Java commonly uses three comment forms: single-line comments, multi-line comments, and documentation comments.

What symbol is used for a single-line comment?

Two forward slashes are used:

//

Everything after // on that line is treated as a comment.

What is a multi-line comment?

A multi-line comment begins with /* and ends with */. It can contain text across multiple lines.

What is a documentation comment?

A documentation comment begins with /** and ends with */. It is designed to document Java classes, methods, fields, and other API elements and can be processed by the Javadoc tool.

What is Javadoc?

Javadoc is a Java documentation tool that processes documentation comments and can generate HTML-based API documentation.

Are comments executed by the JVM?

No. Comments are not executable Java statements.

Can comments be used to disable code?

Yes. Developers can temporarily comment out code during development, although permanently keeping obsolete code commented out is generally discouraged when version control is available.

What is the difference between /* */ and /** */?

/* */ creates a normal multi-line comment, while /** */ creates a documentation comment intended for Javadoc and similar documentation tools.

Should every line of Java code have a comment?

No. Excessive comments can make code harder to read. Comments should provide useful information, especially when explaining complex logic, important decisions, or API behavior.