In this tutorial, you will learn about Java comments, why we use them, and how to use comments in right way.
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments are ignored by the compiler while compiling a code.They are mainly used to help programmers to understand the code.
For example,
// declare and initialize two variables
int a =23;
int b = 46;
// print the output
System.out.println("Codemistic");
Single-line comments allow narrative on only one line at a time. Single-line comments can begin in any column of a given line and end at a new line or carriage return.The // character sequence marks the text following it as a single-line comment.
it is also known as End of Line comment.
Syntax:
//Comments here( Text in this line only is considered as comment )
Here’s an example:
//Java program to show single line comments
class SingleComment
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single line comment above");
}
}
Multi-line comments have one or more lines of narrative within a set of comment delimiters. The /* delimiter marks the beginning of the comment, and the */ marks the end. You can have your comment span multiple lines and anything between those delimiters is considered a comment.To describe a full method in a code or a complex snippet single line comments can be tedious to write, since we have to give ‘//’ at every line.To over come the multi line comments can be used.This type of comment is also known as Traditional Comment.
Syntax:
/*Comment starts
This is
Multi-line
comment
.
.
Commnent ends*/
Here’s an example:
//Java program to show multi line comments
class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}
}
The special comments in the Java source code that are delimited by the /** ... */ delimiters. These comments are processed by the Javadoc tool to generate the API docs. The JDK tool that generates API documentation from documentation comments.
Syntax:
/**Comment starts
*this
*is
*Documatation
*comment
*
*
*Commnent ends*/
Here’s an example:
/** 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;}
} Comment line 3*/
}