Comments
Comments are lines (or blocks) in your source code that the Java compiler completely ignores — they exist purely for humans. Writing good comments is one of the fastest ways to make your code more maintainable, more readable, and easier to debug.
Why Comments Matter
Before diving into syntax, it helps to understand what comments are for:
- Explain the “why”, not just the “what” — the code already shows what it does; comments tell readers why it does it that way.
- Warn about non-obvious behaviour — edge cases, known limitations, workarounds for library bugs.
- Generate API documentation — Javadoc comments turn into browsable HTML docs that tools like Maven and IDEs display automatically.
- Temporarily disable code while debugging (though version control is a better long-term solution).
Java has three comment styles, each with a distinct purpose.
Single-Line Comments
A single-line comment starts with // and runs to the end of that line. It’s the most common style for quick, inline explanations.
public class Circle {
// π to enough decimal places for most calculations
private static final double PI = 3.14159265358979;
public double area(double radius) {
return PI * radius * radius; // A = πr²
}
}
You can place a single-line comment at the end of a code line (called a trailing comment) or on its own line above the code it explains. Both are valid; choose whichever reads more naturally.
Tip: Prefer placing a comment above the line rather than trailing it — it keeps line length short and is easier to read on small screens.
Multi-Line Comments
A multi-line comment starts with /* and ends with */. Everything between those delimiters — including newlines — is ignored by the compiler.
/*
* This method uses the Babylonian method for computing square roots.
* It converges in O(log n) iterations and is accurate to double precision.
* Avoid passing negative numbers — use Math.sqrt() if you need NaN handling.
*/
public double sqrt(double n) {
double guess = n / 2.0;
while (Math.abs(guess * guess - n) > 1e-10) {
guess = (guess + n / guess) / 2.0;
}
return guess;
}
The leading * on each interior line is a style convention (not required) that many formatters and IDEs enforce automatically.
Warning: Multi-line comments cannot be nested.
/* outer /* inner */ */will fail — the compiler sees the first*/as the end of the entire comment, leaving the trailing*/as a syntax error.
Javadoc Comments
Javadoc comments start with /** (two asterisks) and end with */. They are the standard way to document public classes, interfaces, methods, constructors, and fields in Java. The javadoc tool (and every major IDE) parses these comments and renders them as formatted HTML documentation.
Javadoc for a Class
/**
* Represents a 2D point in Cartesian coordinates.
*
* <p>All distance calculations use double-precision floating-point arithmetic.
* Thread-safe: instances are immutable after construction.</p>
*
* @author Jane Developer
* @version 1.0
* @since Java 11
*/
public final class Point {
private final double x;
private final double y;
/**
* Creates a new Point at the given coordinates.
*
* @param x the horizontal position
* @param y the vertical position
*/
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Calculates the straight-line (Euclidean) distance to another point.
*
* @param other the target point; must not be {@code null}
* @return the distance, always >= 0
* @throws NullPointerException if {@code other} is null
*/
public double distanceTo(Point other) {
double dx = this.x - other.x;
double dy = this.y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
Common Javadoc Tags
| Tag | Purpose | Example |
|---|---|---|
@param name description | Documents a method/constructor parameter | @param radius the circle's radius in metres |
@return description | Documents the return value | @return the area, never negative |
@throws ExType description | Documents a checked or notable unchecked exception | @throws IllegalArgumentException if radius < 0 |
@see reference | Cross-reference to a related class/method | @see Math#sqrt(double) |
@since version | First version this API appeared in | @since 17 |
@deprecated reason | Marks an API as obsolete | @deprecated Use {@link #newMethod()} instead |
{@code text} | Inline monospace code | {@code null} |
{@link Class#method} | Clickable hyperlink to another API | {@link String#trim()} |
Tip: In modern Java projects, you can also use Markdown inside Javadoc comments (Java 23 preview, but widely supported by tools from Java 21 onwards via Markdown Doclet plugins). For standard Java 21 LTS, stick with HTML tags like
<p>,<pre>,<ul>inside Javadoc.
Commenting Out Code
During development you might temporarily disable a block of code to test something:
public void process(int[] data) {
// TODO: re-enable validation once input sanitizer is wired up
// if (data == null || data.length == 0) {
// throw new IllegalArgumentException("data must not be empty");
// }
for (int value : data) {
System.out.println(value);
}
}
Warning: Don’t leave commented-out code in production. It clutters the file, confuses readers, and is already preserved in your version history. Delete it and trust
git.
Good vs. Bad Comments
Not all comments are helpful. Here’s a quick comparison:
| Bad comment | Why it’s bad | Better approach |
|---|---|---|
i++; // increment i | Restates the code, adds no insight | Delete it |
// DO NOT CHANGE | No explanation of why or what breaks | // Must stay ≤ 255 — legacy network protocol limit (RFC 867) |
| Giant commented-out block | Dead code creates noise | Delete; git history has it |
| No comment on a complex regex | Leaves readers guessing | Add a comment explaining what the regex matches |
The golden rule: comment the intent and reasoning, not the mechanics.
Under the Hood
Comments are stripped out entirely during the lexical analysis (scanning) phase of the Java compiler — long before bytecode is generated. They have zero cost at runtime: no memory, no CPU cycles, nothing in the .class file.
Javadoc comments are a partial exception: the javadoc tool reads the source file (not the .class file) and extracts /** ... */ blocks. The compiler itself still discards them. The @Deprecated annotation (@Deprecated on the element, not the Javadoc tag @deprecated) is the only comment-adjacent construct that does make it into bytecode — it causes the compiler to emit a deprecation warning at call sites.
You can verify comment stripping yourself with the javap tool:
javap -c Circle.class
You’ll see bytecode instructions but none of your comments.
Quick Reference
// Single-line — best for brief inline notes
/*
* Multi-line — best for longer explanations
* that span several sentences.
*/
/**
* Javadoc — best for public API documentation.
*
* @param value the input value
* @return the processed result
*/
Related Topics
- Java Keywords — see which words are reserved so you know comments can never clash with them
- Naming Conventions — good names reduce the need for comments in the first place
- How a Java Program Runs — understand the compilation pipeline that strips comments out
- javap Tool — verify what actually ends up in your
.classfile - Java Best Practices — broader guidelines including when and how to comment effectively
- Clean Code in Java — principles for writing self-documenting code that needs fewer comments