Java Comments

In Java, comments are lines of code or text that are ignored when the application is executed. The primary purpose of Java comments is:

  • The comments can make your code easier to read. The comments also help other programmers to read and understand your code.
  • You can comment the code, preventing execution of the code written in comments.

There are three type of comments in Java language.

  1. Single Line Comments
  2. Multi-line Comments
  3. Javadoc comments

Single Line Comment

Any text after // on a single line will be ignored and not executed in Java.

This is an example of single line comment before line of code to explain the code.

// Declare x, and assign value of 2
int x = 2;

Here's another example of a single-line comment placed at the end of a code line to provide an explanation. In this scenario, Java will ignore any text following the //.

int x  = 2;  // Declare variable x, and assign value of 2
x + 1;  // Add value of 1 to x

Following line of code will be ignored by Java, and from execution as well.

//int x = 2; 

Multi-line Comments

Multi-line comments in the code are delimited by /* and */ characters. These multi-line comments can span over multiple lines.  The multi-line comments may not be nested. 

This example creates a multi-line comments to explain the following code.

/* This is 
*  Multiple line 
*  comment
*/

You can also use multi-line comment to prevent execution of block of code.

/*
  int x = 5
  x + 1;
*/

Javadoc Comments

This type of comment resembles a multiline comment but has a distinct beginning with /**. This unique syntax tells the Javadoc tool to take note of the comment. Javadoc comments follow a specific format that the Javadoc tool can interpret.

/**
 * Javadoc multiple-line comment
 * @author Mubasher Alam
 */