Codectionary / Developer documentation / Java

Comments & Javadoc

Java supports single-line comments with //, multi-line comments with /* */, and a special documentation format called Javadoc, written as /** */. Javadoc comments support tags like @param, @return, and @throws, and can be processed by the javadoc tool to automatically generate HTML API documentation - the same format used for Java's own official standard library docs.

Syntax

// single-line\n/* multi-line */\n/** Javadoc */

Examples

Single-Line and Multi-Line Comments

The two basic comment styles for explaining code.

// Calculate the area of a rectangle
int width = 5;
int height = 3;

/*
 * This is a multi-line comment.
 * It can span several lines and is often
 * used for longer explanations.
 */
int area = width * height;
System.out.println(area);

Javadoc Comments

Documenting a method's purpose, parameters, and return value in a format tools can process.

public class MathUtils {
    /**
     * Calculates the average of two numbers.
     *
     * @param a the first number
     * @param b the second number
     * @return the average of a and b
     */
    public static double average(double a, double b) {
        return (a + b) / 2;
    }
}

Commenting Out Code

Temporarily disabling a line while debugging.

int total = 0;
for (int i = 1; i <= 10; i++) {
    total += i;
    // System.out.println("Running total: " + total);  // disabled for now
}
System.out.println(total);

Best practices

  • Write Javadoc comments for every public class and method so IDEs can show helpful tooltips and documentation tools can generate API docs
  • Explain *why* code does something in comments, not *what* it does - the code itself should already communicate the "what"
  • Keep comments up to date - an outdated comment that contradicts the code is more harmful than no comment at all
  • Use @param, @return, and @throws tags consistently in Javadoc so generated documentation is complete and useful

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading