Java Comments

Su Suriya Ravichandran Updated 14 Nov 2026
5 min read ·Lesson 4 of 306

Comments are text the compiler ignores. They exist for people: to explain why code does something, to document how to use a class or method, and to temporarily disable code during debugging. Java has three kinds, each with a specific purpose.

Single-Line Comments

A single-line comment starts with // and runs to the end of the line.

int retries = 3; // number of attempts before giving up

// Reset the counter before the next batch
retries = 0;

Everything after // on that line is ignored, including code. The comment can sit on its own line or follow a statement.

int total = price * quantity; // + tax;   <-- "+ tax" is NOT compiled

This makes // the usual tool for commenting out a single statement while testing:

System.out.println("Debug: value = " + value);
// System.out.println("Old debug line, kept for reference");

Multi-Line Comments

A multi-line comment starts with /* and ends with */. It can span any number of lines.

/*
 * Calculates compound interest.
 * Formula: A = P(1 + r/n)^(nt)
 * The leading asterisks on each line are a convention, not syntax.
 */
double amount = principal * Math.pow(1 + rate / n, n * years);

It can also appear in the middle of a line, because it has an explicit terminator:

int result = compute(/* base */ 10, /* exponent */ 2);

This inline form is occasionally used to label arguments whose meaning is unclear from the call alone.

Multi-line comments do not nest

/*
   int x = 1;
   /* inner comment */     <-- this */ closes the OUTER comment
   int y = 2;              <-- this is now compiled, and will error
*/

The first */ encountered ends the comment, regardless of how many /* preceded it. This is why commenting out a block that already contains a multi-line comment fails. Use // on each line instead (every IDE has a shortcut, usually Ctrl+/), which has no such problem.

Documentation Comments (Javadoc)

A documentation comment starts with /** (two asterisks) and ends with */. It is placed immediately before a class, interface, method, field, constructor, or record. The javadoc tool reads these comments and generates HTML API documentation; IDEs display them as hover tooltips.

/**
 * Represents a bank account with a non-negative balance.
 * Instances are not thread-safe.
 */
public class BankAccount {

    private double balance;

    /**
     * Deposits money into the account.
     *
     * @param amount the amount to deposit; must be greater than zero
     * @throws IllegalArgumentException if {@code amount} is zero or negative
     */
    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
        balance += amount;
    }

    /**
     * Returns the current balance.
     *
     * @return the balance, never negative
     */
    public double getBalance() {
        return balance;
    }
}

How Javadoc is structured

The first sentence is the summary, shown in index listings; it should state what the element does. Following paragraphs give detail. Then come block tags, each on its own line:

TagUsed onMeaning
@param name descriptionMethods, constructors, generic typesDescribes one parameter; one tag per parameter
@return descriptionNon-void methodsDescribes the returned value
@throws Type descriptionMethods, constructorsDescribes when an exception is thrown
@see ReferenceAnyCross-reference to a related class or method
@since versionAnyVersion in which the element was added
@deprecated reasonAnyMarks the element obsolete and says what to use instead

Inline tags appear inside the description text:

  • {@code expr} renders expr in monospace and prevents HTML interpretation. Use it for identifiers, literals, and short expressions.
  • {@link Class#method} creates a hyperlink to another documented element.
/**
 * Parses the input using {@link #parse(String)} and caches the result.
 * Returns {@code null} if the input is empty.
 */

Generating the documentation

javadoc -d docs src/com/example/*.java

This writes HTML files into the docs directory. Build tools (Maven's javadoc:javadoc goal, Gradle's javadoc task) do the same for an entire project. The standard library's own documentation at docs.oracle.com is produced this way from Javadoc comments in the JDK source.

Where Javadoc matters

Any code that other developers call, whether a public library or a shared module inside a company, should document its public API with Javadoc. The comment is the contract: what the method expects, what it guarantees, what can go wrong. For private helper methods used in one place, a plain // comment, or no comment, is usually enough.

Comments Inside Strings

Comment markers inside a string literal are ordinary characters:

String url = "https://example.com"; // the // inside the string is part of the URL
String note = "/* not a comment */";

The compiler recognizes string literals before it looks for comments, so the // in the URL does not start a comment.

What to Comment

The compiler does not care what comments say, but their value depends on it. Code already states what happens; a comment restating it adds nothing:

i++; // increment i

A comment earns its place when it explains something the code cannot: the reason behind a choice, a non-obvious constraint, a reference to a bug or specification, or a warning about a subtle behavior.

// Use a LinkedHashMap so that iteration order matches insertion order;
// the export format requires fields in the order they were registered.
Map<String, Field> fields = new LinkedHashMap<>();

// Retry on 429 only. 5xx errors are handled by the circuit breaker upstream.
if (status == 429) {
    retry();
}

Comments also go stale. When code changes and the comment does not, the comment becomes actively misleading, which is worse than no comment. Treat comments as part of the code to be updated in the same edit.

TODO and FIXME Markers

By convention, comments beginning with TODO or FIXME mark unfinished or known-broken code. IDEs collect these into a task list.

// TODO: replace with a bounded cache once the memory limits are decided
// FIXME: fails for dates before 1970 because of negative epoch values

These are ordinary comments to the compiler; the keywords are recognized only by tooling.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Comments and get answers drawn from it.

Signed-in readers only.