Java 注释
单行注释、多行注释与文档注释的写法与用途。
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
5With 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.
单行注释
// 之后到行尾都是注释。适合写在一行代码的末尾,解释这行的意图;也适合临时注释掉一行代码调试。
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多行注释
/* 与 */ 之间全部是注释,可以跨行。注意它不能嵌套 —— 里面再出现 /* 不会开启新的一层。
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文档注释
/** ... */ 是文档注释,写在类、方法、字段声明之前,可带 @author、@param、@return、@throws 等标签。用 javadoc 命令能直接生成 HTML API 文档。
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
5IDE 里把光标停在方法上按 Ctrl+Q(IDEA)或 F2(Eclipse),看到的就是文档注释内容 —— 这是给调用者看的说明,不是给编译器看的。