java注释是不会被编译器和解释器执行的语句。 注释可以用于提供关于变量,方法,类或任何语句的信息或解释。 它也可以用于在特定时间隐藏程序代码。
在java中有3
种类型的注释。它们分别如下 -
单行注释仅用于注释一行,它使用的是 //
两个字符作为一行注释的开始,如下语法所示 -
语法:
// this is single line comment
示例:
public class commentexample1 {
public static void main(string[] args) {
int i = 10;// here, i is a variable
system.out.println(i);
int j = 20;
// system.out.println(j); 这是另一行注释,这行代码不会被执行。
}
}
上面示例代码输出结果如下 -
10
多行注释用于注释多行代码。它以 /*
开始,并以 */
结束,在 /*
和 */
之间的代码块就是一个注释块,其中的代码是不会这被执行的。
语法:
/*
this
is
multi line
comment
*/
示例:
public class commentexample2 {
public static void main(string[] args) {
/*
* let's declare and print variable in java.
*
* 这是多行注释
*/
int i = 10;
system.out.println(i);
}
}
上面示例代码输出结果如下 -
10
文档注释用于创建文档api。 要创建文档api,需要使用javadoc
工具。
语法:
/**
this
is
documentation
comment
*/
示例:
/**
* the calculator class provides methods to get addition and subtraction of
* given 2 numbers.
*/
public class calculator {
/** the add() method returns addition of given numbers. */
public static int add(int a, int b) {
return a + b;
}
/** the sub() method returns subtraction of given numbers. */
public static int sub(int a, int b) {
return a - b;
}
}
通过javac
工具编译:
javac calculator.java
通过javadoc
工具创建文档api:
javadoc calculator.java
现在,将在当前目录中为上面的calculator
类创建了html文件。 打开html文件,并查看通过文档注释提供的calculator
类的说明。如下所示 -