How to write comments in Java

Introduction

In Java, comments are used to add notes to the programs. They serve to document the code and make it more readable.

Generally, comments are used to explain what the code is doing. This is a good practice, as it makes it more understandable for you to refer back to later or for others who might want to read your code.

Comments are ignored by Java Compiler. Java supports three kinds of comment statement, as shown below:

1. Single line comment

// This is a comment. 
// it starts with two forward slashes and spans until end of line.
// Leading spaces before the delimiter are ignored. 

The text followed by // will be ignored by the compiler until the end of the line.

2. Multi-line comment

/* This type of comment starts 
   with forward slash followed by an astrisk
   and can span multiple lines 
   until astriks followed by a forward slash */

The text between /* and */ will be ignored by the compiler.

Note: Java does not support nesting of multi-line comments.

3. Documentation comments

The javadoc tool of JDK is used to generate documentation in HTML format from your source code.

/** This is a documentation comment 
    which starts with a forward slash followed by two asterisk,
    and ends with an asterisk followed by a forward slash
*/

The text between /** and */ will be ignored by the compiler.

Free Resources