Java Comments
In computer languages, comments are an important component of the language, used to explain the role of code in source code, which can enhance the readability and maintainability of a program.
A Java comment is text used in a Java program to provide explanations of code functionality.
Comments are not included by the compiler in the final executable program, so they do not affect the program's execution.
Comments are a good programming habit; they help programmers more easily understand the purpose and functionality of code, and are very useful in team collaboration.
There are mainly three types of Java comments:
- Single-line comment
- Multi-line comment
- Documentation comment
Single-line comment
A single-line comment starts with a double slash
//
to begin:
Example
//
This is a single-line comment
int
x
=
10
;
//
Initialize a variable x to 10
Multi-line comment
A multi-line comment starts with /* and ends with */:
Example
/*
This is a multi-line comment that can be used to comment out multiple lines of code
*/
int
y
=
20
;
//
Initialize a variable y to 20
Documentation comment
A documentation comment starts with /** and ends with */, usually appearing before the declaration of a class, method, field, etc., used to generate code documentation. Such comments can be extracted by tools to generate API documentation, such as JavaDoc.
Example
/*
-
- This is a documentation comment example * It usually contains detailed information about the class, method, or field
*/
public
class
MyClass
{
//
Members and methods of the class
}
The format of a documentation comment usually contains some specific tags, such as @param for describing method parameters, @return for describing return values, and @throws for describing possible exceptions, etc. These tags help generate clear API documentation so that other developers can better understand and use your code.
For more on documentation comments, refer to:Java Documentation Comments.