Java 注释

单行注释、多行注释与文档注释的写法与用途。

Beginner
Key Points`//` 单行、`/* */` 多行、`/** */` 文档注释;文档注释能被 javadoc 提取成 HTML 文档。

单行注释

Everything after // to the end of the line is a comment — good for explaining a single statement or temporarily disabling one while debugging.

Java
public class Single {
    public static void main(String[] args) {
        // 这是一个单行注释
        System.out.println("Hello");   // 行尾注释

        int price = 100;
        // int price = 200;  // 被注释掉,不会执行
        System.out.println(price);
    }
}
Output
Hello
100

多行注释

Everything between /* and */ is a comment and may span lines. It does not nest — a /* inside does not open a new level.

Java
public class Multi {
    public static void main(String[] args) {
        /*
         * 这是多行注释。
         * 常用于临时屏蔽一整段代码,
         * 或解释一段复杂逻辑。
         */
        System.out.println("after block comment");

        int a = 1;
        /*
        int b = 2;
        System.out.println(a + b);
        */
        System.out.println(a);
    }
}
Output
after block comment
1

文档注释

/** ... */ is a documentation comment placed before a class, method or field. It accepts tags like @author, @param, @return and @throws, and javadoc turns it into HTML API docs.

Java
/**
 * 计算工具类。
 *
 * @author BackendWiki
 * @version 1.0
 */
public class Doc {
    /**
     * 求两个整数之和。
     *
     * @param a 第一个加数
     * @param b 第二个加数
     * @return 两数之和
     */
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
    }
}
Output
5
With the cursor on a method, Ctrl+Q (IDEA) or F2 (Eclipse) shows the doc comment — it is documentation for callers, not instructions to the compiler.

Friends & Partners