Java comments are used to add notes and explanations to your code that are not executed as part of the program.
There are three types of comments in Java:
-
Single-line comments: These comments begin with two forward slashes
//
and continue until the end of the line. Single-line comments are used to add short notes to the code.Example:
// This is a single-line comment
int x = 10; // This is also a single-line comment
-
Multi-line comments: These comments begin with
/*
and end with*/
. Multi-line comments can span across multiple lines and are used to add longer notes to the code.Example:
/*
This is a multi-line comment.
It can span across multiple lines.
*/
int y = 20; // This is not a comment
-
Javadoc comments: These comments begin with
/**
and end with*/
. Javadoc comments are used to generate documentation for your code. Javadoc comments can include tags that provide information about the code, such as@param
,@return
,@throws
, etc.Example:
/**
* This method adds two numbers.
* @param a the first number to add
* @param b the second number to add
* @return the sum of a and b
*/
public int add(int a, int b)
{
return a + b;
}
It’s important to note that comments are ignored by the Java compiler and are not executed as part of the program. They are used to improve the readability and maintainability of your code by providing additional information about the code to other programmers who may read it in the future.