Java Comments

Java Comments
••• Java Comments

In this article, you will learn about Java comments, and why and how to use them.

In programming, comments are portion of the program intended for you and your fellow programmers to understand the code. They are completely ignored by Java compilers.

In Java programming language, there are two types of comments:

  • /* ... */
  • // ....

Traditional comment /* … */


This is a multiline comment that can span over multiple lines. The Java compiler ignores everything from /* to */. For example,

/* This is a multi-line comment.
 * The problem prints "Hello, World!" to the standard output.
 */
class HelloWorld {
    public static void main(String[] args) {    	
    	 {	
    		 System.out.println("Hello, World!");
    	 }
    }
}

Here, the comment is

/* This is a multi-line comment.
 * The problem prints "Hello, World!" to the standard output.
 */

End of Line Comment //


The compiler ignores everything from // to the end of the line. For example,

// "Hello, World!" program
 
class AssignmentOperator {
    public static void main(String[] args) {    	
    	 {	
    		 System.out.println("Hello, World!"); // prints "Hello, World!"
    	 }
    }
}

The program above contains two end of line comments:

// "Hello, World!" program

and

// prints "Hello, World!"

Use Comments the Right Way


Comments shouldn’t be the substitute for a way to explain poorly written code in English. Write well structured and readable code, and then use comments.

Some believe that code should be self-documenting and comments should be scarce. However, I have to disagree with it completely (It’s my personal opinion). There is nothing wrong with using comments to explain complex algorithms, regex or scenarios where you have chosen one technique over other (for future reference) to solve the problem.

In most cases, use comments to explain ‘why’ rather than ‘how’ and you are good to go.