Java 评论
Java 注释
在本教程中,您将了解 Java 注释、我们使用它们的原因以及如何正确使用注释。
在计算机编程中,注释是程序中被 Java 编译器完全忽略的一部分。它们主要用于帮助程序员理解代码。例如,
// declare and initialize two variables
int a =1;
int b = 3;
// print the output
System.out.println("This is output");
在这里,我们使用了以下评论,
- 声明和初始化两个变量
- 打印输出
Java 中的注释类型
在 Java 中,有两种类型的注释:
- 单行注释
- 多行注释
单行注释
单行注释在同一行开始和结束。要编写单行注释,我们可以使用 //
象征。例如,
// "Hello, World!" program example
class Main {
public static void main(String[] args) {
{
// prints "Hello, World!"
System.out.println("Hello, World!");
}
}
输出 :
Hello, World!
在这里,我们使用了两个单行注释:
- “你好,世界!”程序示例
- 打印“Hello World!”
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 编译器会忽略 /*
中的所有内容 到 */
.
正确使用评论
您应该始终考虑的一件事是,注释不应该替代用英语解释写得不好的代码的方式。您应该始终编写结构良好且自我解释的代码。然后,使用注释。
有些人认为代码应该是自描述的,并且应该很少使用注释。但是,在我个人看来,使用评论并没有错。我们可以使用注释来解释复杂的算法、正则表达式或我们必须在不同技术中选择一种技术来解决问题的场景。
注意 :在大多数情况下,总是使用注释来解释“为什么 ' 而不是 '如何 ' 然后你就可以走了。
java