在上一个教程中,您学习了如何编写第一个 Java 程序。现在,让我们来学习 Java 注释。
提示:我们在这本教程系列中较早介绍注释,因为从现在开始,我们将使用它们来解释我们的代码。
注释是我们添加到代码中的提示,可以使代码更容易阅读和理解。
Java 编译器会完全忽略注释。
例如,
class HelloWorld {
public static void main(String[] args) {
// print Hello World to the screen
System.out.println("Hello World");
}
}
输出
Hello World
这里,// print Hello World to the screen
是 Java 编程中的一个注释。Java 编译器会忽略 //
符号之后的所有内容。
注意:您可以忽略编程概念,只需专注于注释。我们将在后续教程中重新审视这些概念。
单行注释
在 Java 中,单行注释在同一行开始和结束。要编写单行注释,我们可以使用 //
符号。例如,
// declare and initialize two variables
int a = 1;
int b = 3;
// print the output
System.out.println("This is output");
这里,我们使用了两个单行注释
// 声明并初始化两个变量
// 打印输出
Java 编译器会忽略从 //
到行尾的所有内容。因此,它也被称为行尾注释。
多行注释
当我们想在多行中编写注释时,可以使用多行注释。要编写多行注释,我们可以使用 /*....*/
符号。例如,
/* This is an example of multi-line comment.
* The program prints "Hello, World!" to the standard output.
*/
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
输出:
Hello, World!
这里,我们使用了多行注释
/* This is an example of multi-line comment.
* The program prints "Hello, World!" to the standard output.
*/
这种类型的注释也称为传统注释。在这种类型的注释中,Java 编译器会忽略从 /*
到 */
的所有内容。
使用注释阻止代码执行
在调试时,可能会出现我们不希望某些代码执行的情况。例如,
public class Main {
public static void main(String[] args) {
System.out.println("some code");
System.out.println("error code");
System.out.println("some other code");
}
}
如果在运行程序时出现错误,我们可以使用注释来禁用出错的代码,而不是删除它,这可以成为一个有价值的调试工具。
public class Main {
public static void main(String[] args) {
System.out.println("some code");
// System.out.println("error code");
System.out.println("some other code");
}
}
为什么使用注释?
我们应该出于以下原因使用注释:
- 注释使我们的代码更具可读性,便于将来参考。
- 注释用于调试目的。
- 我们可以使用注释进行代码协作,因为它可以帮助其他开发人员理解我们的代码。
注意:注释不是也不应该被用作解释写得不好的代码的替代品。总是努力编写清晰、易于理解的代码,然后将注释作为补充。
在大多数情况下,总是使用注释来解释“为什么”而不是“怎么做”,这样就足够了。
接下来,我们将学习 Java 变量和字面量。