Java Comments

In all programming languages including Java, Comments are statements and sentences in a code that have no impact on the functionality of code. They are ignored by Java compiler. The purpose of adding comments to a code is to increase the readability of code. And to get a better understanding of working of the code. The complex programs without comments are difficult to understand and hence it becomes difficult for the developer to later edit them. The best practice is to add comments in your program.

Another purpose of comments is to get a quick fix for removing some code and test the execution of rest of the code without actually having to remove the code. You can comment the undesirable portion of code and check execution. After commenting, user can also uncomment the section of code.

Comments Syntax

Java programming language allows its users to comment out a piece of code.

Types of comments in Java

There can be two types of comments in java program:

  • Single line comments
  • Multi line comments

Single line comments

User can comment out a single line in the code by using double forward slashes (//). Any thing that follows the double forward slashes till the end of line is considered to be a comment and is ignored by the compiler. The syntax to comment out a single line is:

Example

The below code prints the text “Hello World!” on command line.

// File name is MyProgram.java
public class MyProgram {                  // Class Name
   public static void main(String []args) {
      System.out.println("Hello World!"); // prints Hello World!
   }
}

Here, the sentences “Class Name” and “prints Hello World!” are single line comments and are ignored. The output of the above program after compilation will be: Hello World!

Multi line comments

Rather than commenting single lines separately, java allows its user to comment out a chunk of code using a combination of forward slash(/) and asterisk sign (*). The multi line comments start from the sign /* and end at the sign */. The lines of code present between /* and */ will be the comments and it will be ignored by the compiler. The syntax to comment out multiple lines from a code is:

Example

Here is a code that contains multi line comments. It will print the text “Hello World!” on console.

// File name is MyProgram.java
public class MyProgram {  
   */ This code prints the
   text "Hello World!" on console */            
   public static void main(String []args) {
      System.out.println("Hello World!"); 
   }
}

Here, the sentence “This code prints the text “Hello World!” on console” is a multi line comment and is ignored. The output of the above program after compilation will be: Hello World!

The location of comments inside Java file does not matter. It can be inside or outside a class or method.

Blank line

Blank line is a line that contains only white spaces. Java compiler ignores blank lines inside a comment.