Comments

Java offers three comment forms — line, block, and Javadoc — for explaining code to humans and, in Javadoc's case, generating API documentation.

Comments are text the compiler ignores, meant purely for human readers (or, for Javadoc comments, for documentation-generation tooling). Java supports three forms: single-line, multi-line block, and documentation (Javadoc) comments. Used well, they clarify intent that code alone cannot express; used poorly, they restate the obvious or rot into lies as code changes around them.

Single-Line Comments (//)

Everything from // to the end of the line is ignored by the compiler. Single-line comments are the most common form for brief, local explanations.

int retries = 3; // number of retry attempts before giving up
// TODO: make this configurable via a settings file

Multi-Line Block Comments (/* */)

Everything between /* and */ is ignored, including across multiple lines. Block comments cannot be nested — a /* inside another /* .. */ does not start a new nested comment, it just becomes ordinary text until the first */ closes the whole block.

The first */ closes the block comment; block comments do not nest, so anything after that point is parsed as ordinary Java code and will typically cause a syntax error.

/*
 * Computes compound interest.
 * Assumes annualRate is expressed as a decimal (e.g. 0.05 for 5%).
 */
double computeInterest(double principal, double annualRate, int years) {
    return principal * Math.pow(1 + annualRate, years);
}
/* outer comment /* nested attempt */ this text is NOT a comment, it's code! */

Documentation Comments (/** */) and Javadoc

A comment starting with /** (two asterisks) is a documentation comment. Placed immediately before a class, interface, method, or field declaration, it is picked up by the javadoc tool to generate HTML API documentation. Javadoc comments use special tags starting with @ to describe parameters, return values, exceptions, and more.

Common Javadoc tags: @param, @return, @throws (or the older @exception), @see, @since, @deprecated, @author. Running the javadoc command-line tool over annotated source produces browsable HTML documentation, which is how most published Java library documentation (including the JDK's own API docs) is generated.

/**
 * Computes compound interest for a given principal.
 *
 * @param principal the initial amount invested
 * @param annualRate the annual interest rate, expressed as a decimal (e.g. 0.05 for 5%)
 * @param years the number of years the investment is held
 * @return the final amount after compounding
 * @throws IllegalArgumentException if years is negative
 */
double computeInterest(double principal, double annualRate, int years) {
    if (years < 0) {
        throw new IllegalArgumentException("years cannot be negative");
    }
    return principal * Math.pow(1 + annualRate, years);
}

Comment Best Practices

Good comments explain why, not what — the code itself already says what it does; a comment earns its place by explaining a non-obvious reason, trade-off, or constraint. Comments should be kept in sync with the code they describe; a stale comment that contradicts the code it sits next to is often worse than no comment at all, because it actively misleads readers.

Favor Javadoc comments on public API elements (classes, public methods) so consumers of your code get generated documentation. Reserve inline // comments for clarifying tricky local logic, not for narrating every line.

Comments Versus Self-Documenting Code

Well-chosen names and small, focused methods often communicate intent better than a comment ever could — this is sometimes called 'self-documenting code.' A comment that merely restates what a well-named line already says adds noise, not clarity.

The goal is not 'zero comments' — even well-named code benefits from a comment explaining a business rule, a workaround for a known bug, or a non-obvious algorithmic choice. The goal is comments that add information the code cannot express on its own.

// bad: comment just restates the code
int d; // elapsed time in days
d = 0;

// better: the name itself carries the meaning
int elapsedDays = 0;

Where Comments Can Legally Appear

Comments may appear almost anywhere whitespace is allowed between tokens: before a statement, at the end of a line, inside an expression's argument list, or between declarations. They cannot appear inside a string or character literal (a // or /* inside quotes is just ordinary text, not a comment) and cannot split a single token in two.

int sum = add(1, /* first operand already added */ 2);
String url = "https://example.com"; // the // here is just text inside the string literal, not a comment

TODO/FIXME Conventions

Many teams adopt an informal convention of marking unfinished or known-problematic code with a tagged comment such as // TODO: or // FIXME:, which IDEs and some build tools can scan for and surface in a task list. Java itself attaches no special meaning to these tags — they are a team/tooling convention, not a language feature.

// TODO: replace with a configurable retry policy once the settings API lands
// FIXME: this throws NullPointerException when input is empty — needs a guard clause

Key Takeaways

// starts a comment that runs to the end of the line; /* */ delimits a comment that can span multiple lines but cannot nest.

/** */ documentation comments, placed before a declaration, are read by the javadoc tool to generate HTML API documentation.

Common Javadoc tags include @param, @return, @throws, @since, and @deprecated.

Good comments explain why the code does something, not what it does — self-documenting names and structure should carry the 'what.'

A stale comment that no longer matches the code can be more harmful than no comment at all.

/* outer /* inner */ still inside? */ // use single-line comments for consecutive lines instead of attempting nested block comments // outer // inner

Java block comments do not nest; the first */ closes the comment early, and the remaining text is parsed as code, usually causing a syntax error.

// increments i by 1 i++;

// advance to the next retry attempt i++;

A comment that merely restates the literal code (increments i by 1) adds no information beyond what the code already says; a useful comment explains intent or reasoning instead.

What are the three comment forms in Java, and which one is processed by an external tool?

Single-line (//), multi-line block (/* */), and documentation comments (/** */); Javadoc comments are processed by the javadoc tool to generate HTML documentation.

Can block comments (/* */) be nested in Java? What happens if you try?

No. The first */ encountered closes the comment, so anything intended as a 'nested' comment becomes ordinary code text, typically causing a syntax error.

Name three common Javadoc tags and what each describes.

@param describes a method parameter; @return describes the return value; @throws (or @exception) describes an exception the method may throw. (@since and @deprecated are also common.)

What is the general guideline for what a good comment should explain?

Why the code does something (intent, reasoning, trade-offs, constraints) rather than what it does, since the code itself already expresses the what.

Why can a stale comment be worse than no comment at all?

Because it actively misleads a reader into believing something about the code's behavior that is no longer true, whereas no comment at least doesn't assert anything false.

Where must a Javadoc comment be placed for the javadoc tool to associate it with a class or method?

Immediately before the declaration of the class, interface, method, or field it documents.

What does 'self-documenting code' mean, and how does it relate to comments?

It means using clear names and well-structured code so that the code's purpose is evident without needing a comment to restate it; it reduces reliance on comments for explaining 'what', freeing comments to explain 'why'.

Write a Javadoc comment for a method boolean isPrime(int n) that documents its parameter, return value, and notes it throws IllegalArgumentException for negative input.

/** * Determines whether the given integer is a prime number. * * @param n the number to test; must be non-negative * @return true if n is prime, false otherwise * @throws IllegalArgumentException if n is negative */ boolean isPrime(int n) { if (n < 0) { throw new IllegalArgumentException("n cannot be negative"); } // ... implementation return false; }

A well-formed Javadoc comment starts with /**, uses @param for each parameter, @return for the return value, and @throws for documented exceptions, placed directly above the declaration.

Is this valid Java, and how many separate block comments does it contain?

Yes, it's valid — two separate, non-nested block comments on one line, each properly opened and closed, with real code (int x = 1;) between them.

Rewrite this poorly commented snippet so the comment adds real value: int t = 30; // set t to 30 int sessionTimeoutSeconds = 30; // matches the load balancer's idle-connection timeout

Renaming t to a descriptive name removes the need to restate 'set t to 30', and the remaining comment now explains why 30 was chosen rather than what the line does.

/* first comment */ int x = 1; /* second comment */