Java Tutorial Series: This lesson is part of our comprehensive Complete Java Tutorial: Learn Java from Beginner to Advanced.

Java Comments: Single-Line, Multi-Line and Documentation Comments

Comments allow developers to explain source code without making those explanations executable. Java defines comments within its lexical structure.

What You Will Learn

  • Single-line comments
  • Multi-line comments
  • Documentation comments
  • Javadoc
  • When comments help
  • When comments become harmful
  • Professional commenting practices

1. What Are Java Comments?

Comments are developer-facing explanations used for intent, assumptions, business rules, constraints, and public APIs. They are most valuable when the reason behind code cannot be expressed clearly by the code itself.

2. Single-Line Comments

The // marker starts a comment that continues to the end of the line.

3. Multi-Line Comments

/*
   Explanation spanning
   multiple lines.
*/
int total = price + tax;

Use block comments when a longer explanation is genuinely useful.

4. Documentation Comments

/**
 * Calculates total price.
 * @param price item price
 * @param quantity item count
 * @return total price
 */
public double calculateTotal(double price, int quantity) {
    return price * quantity;
}

Documentation comments use /** … */ and can be processed by Javadoc tooling.

5. What Good Comments Explain

  • Why a non-obvious approach is required
  • Business rules and constraints
  • Public API behavior
  • Integration assumptions
  • Compatibility considerations

6. What Comments Should Not Do

  • Repeat obvious code
  • Describe behavior that is no longer true
  • Hide confusing design instead of improving it
  • Become long essays inside small methods

7. Comments and Maintainability

A comment becomes technical debt when implementation changes but the comment does not. Review related comments when modifying code.

8. Comments During Debugging

Temporarily commenting out code can help an experiment, but version control, tests, breakpoints, and logging are better long-term debugging tools.

9. Javadoc in Professional Java

Public libraries and internal APIs benefit from documentation that explains parameters, return values, exceptions, and usage expectations.

10. Best Practices

  • Prefer clear code over excessive comments.
  • Explain decisions rather than obvious syntax.
  • Keep API documentation current.
  • Remove temporary debugging comments.
  • Use consistent documentation conventions.

9. Documentation Comments and Javadoc

Documentation comments use the /** … */ form and are intended for API documentation. Tools such as Javadoc can process these comments and generate documentation for classes, methods, fields, and other documented program elements.

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

Documentation comments are especially useful for public classes and methods because they communicate how another developer should use an API. They should describe the contract, important assumptions, parameters, return values, and exceptional behavior when relevant.

10. What Should You Comment?

A strong rule is to comment the reason or intent when the code alone does not make it obvious. Comments can explain a business rule, an unusual workaround, an external constraint, or an important assumption.

// Keep three retry attempts because the external service may be temporarily unavailable.
for (int attempt = 1; attempt <= 3; attempt++) {
    sendRequest();
}

The useful part of the comment is why three attempts are used. A comment that merely repeats the code provides little additional information.

11. Comments That Should Usually Be Avoided

  • Do not comment obvious syntax line by line.
  • Do not leave outdated comments after changing the implementation.
  • Do not use comments to justify confusing code when the code can be made clearer.
  • Do not turn comments into long personal notes or temporary reminders that belong in the project workflow.
// Increment i by 1
i++;

The code already expresses the operation clearly. A better comment is one that adds context the statement cannot provide.

12. Comments and Maintainability

Comments create a maintenance responsibility. If the code changes but the comment does not, the project can contain two conflicting sources of information. For that reason, developers should prefer clear names, focused methods, and simple control flow before adding explanatory comments.

// Business rule: premium customers receive free shipping.
if (customer.isPremium()) {
    shippingCost = 0;
}

This comment is useful because the free-shipping rule is a business decision rather than a purely technical detail.

13. Comments in Debugging and Development

Temporary comments can be useful while exploring a problem, but they should be reviewed before code is committed. Instead of leaving large blocks of disabled code, use version control to preserve previous implementations and keep the active source readable.

// Temporary diagnostic output while investigating the calculation.
System.out.println("total=" + total);

Once the investigation is finished, remove temporary diagnostics if they are no longer part of the application behavior.

14. Commenting Best Practices for Professional Java Code

  • Write comments for intent, business rules, constraints, and public API contracts.
  • Keep comments close to the code they explain.
  • Update comments when behavior changes.
  • Use Javadoc for reusable public APIs where generated documentation is useful.
  • Prefer meaningful names and small methods over explanatory comments for obvious behavior.
  • Review comments during code review just like executable code.

15. Practical Commenting Example

/**
 * Checks whether a customer can place an order.
 * The account must be active and the order total must be positive.
 */
public boolean canPlaceOrder(Customer customer, double total) {
    return customer.isActive() && total > 0;
}

The Javadoc explains the method contract without describing every token. The implementation remains short enough that its actual logic is easy to read.

16. Commenting a Public API

For a reusable class or method, comments should help a developer understand how the API is intended to be used. A useful documentation comment can describe the purpose, parameters, return value, important constraints, and exceptions without explaining every implementation line.

/**
 * Finds the first active account for the supplied customer ID.
 * @param customerId identifier of the customer
 * @return the active account, or null when none exists
 */
public Account findActiveAccount(String customerId) {
    // implementation
    return null;
}

The documentation describes the contract. The implementation can change later without requiring the documentation to describe every internal step.

17. Comments and Code Review

During code review, comments should be checked for accuracy just like code. Reviewers can ask whether a comment explains an important reason, whether the information is still true, and whether the code itself could be clearer. A stale comment can be more harmful than no comment because it creates false confidence.

18. Comments for Business Rules

Business rules are one of the strongest reasons to use comments. A condition such as a particular date, threshold, retry count, or eligibility rule may not be obvious from the code alone.

// Orders above this amount qualify for free shipping under the current policy.
if (orderTotal >= 1000) {
    shippingCost = 0;
}

If the rule changes, the comment must be updated with the implementation. For frequently changing rules, storing the rule in configuration or a business-rule system may be more maintainable than hard-coding it.

19. Comments and TODOs

TODO comments can mark unfinished work, but they should not become a substitute for project tracking. A short TODO can be useful during development, while long-term work should normally be recorded in the team’s issue or task system.

// TODO: replace temporary fallback after the new service endpoint is available.

20. Practice Tasks for Java Comments

  • Convert a useful explanation into a single-line comment.
  • Write a multi-line comment explaining a temporary algorithm assumption.
  • Write Javadoc for a public method with two parameters and a return value.
  • Find three comments in a sample program that simply repeat the code and remove them.
  • Add a comment explaining a non-obvious business rule rather than the syntax itself.

The objective is to develop judgment. Professional commenting is not about having more comments; it is about having the right information in the right place.

21. Comment Quality Checklist

  • Does the comment explain something the code cannot communicate clearly?
  • Is the information still accurate?
  • Is the wording concise and professional?
  • Would a better name or smaller method make the comment unnecessary?
  • For public APIs, would Javadoc provide lasting value?

Practical Mini Project

Take a small Java class that calculates an order total. First write it without comments. Then identify only the places where the reason behind a decision is not obvious from the code. Add a short comment for each business rule and Javadoc for the public calculation method. Finally, remove comments that merely restate syntax. This exercise develops the judgment required for maintainable comments.

Commenting Mini Project

A useful extension is to improve the first version rather than immediately building something large. Give each important value a clear name, keep methods short, validate inputs at the boundary, and test normal, boundary, and invalid cases. This turns a language concept into a small engineering habit.

Comment questions to practice

  • What is the difference between //, /* … */, and /** … */?
  • When should Javadoc be used?
  • What makes a comment harmful?
  • Why do stale comments create maintenance problems?
  • When is a business-rule comment useful?

How This Topic Connects to the Next Java Concepts

After comments, focus on variables and data types. Comments explain intent, while variables and types define the actual data and state used by the program.

22. Comments and Long-Term Maintenance

A useful comment should survive reasonable implementation changes. If a comment describes an internal variable name or repeats the current control flow, it may become obsolete quickly. If it documents a business rule, API contract, compatibility requirement, or unusual constraint, it is more likely to remain valuable. Think about the expected lifetime of the information before deciding to write it into a comment.

23. Comments as Part of Communication

Source code is read far more often than it is written. Comments are therefore part of communication between developers, reviewers, maintainers, and future contributors. Short, accurate explanations of important decisions can reduce the time required to understand a system. The goal is not maximum documentation; the goal is useful context at the point where it matters.

Frequently Asked Questions

Are comments executed?

No.

What starts a single-line comment?

//

What creates a block comment?

/* … */

What is Javadoc?

A documentation system and toolchain based on Java documentation comments.

Should every line have a comment?

No.

Conclusion

Good comments improve communication between developers. Use them for intent and important context while keeping implementation code clear.

  • Java Syntax
  • Java Variables
  • Java Methods
  • Java Packages