Java – Comments

The objective of adding comments to computer code is to make it easier to comprehend. It improves the readability of the code, making it easier to edit afterwards. When the compiler runs the code, it ignores comments. There are two ways to add a comment in Java:

  • Single line comment
  • Block comment

Single Line Comment:

It begins with // and finishes with the line’s end. Anything from // to the end of the line is a single line comment that the compiler will disregard.

Syntax:

//single line comment.
statements; //single line comment.

Example:

The following example shows how to utilise single line comments in a Java programme. When building the code, the compiler ignores the comments.

public class MyClass {
  public static void main(String[] args) {
    //first single line comment.
    System.out.println("Hello World!"); //second single line comment.
  }
}

The output of the above code will be:

Hello World!

To run any of the above codes: Click here

Block Comment:

It begins with the letter /* and finishes with the letter */. Anything between /* and */ is a block comment that the compiler will disregard.

Syntax:

/*block 
comment.*/
statements; /*block comment.*/ statements;

Example:

The following example shows how to utilise multiple line comments in Java code that are ignored by the compiler during compilation.

public class MyClass {
  public static void main(String[] args) {
    /*first 
    block comment. */
    System.out.println(/*second block comment.*/"Hello World!");
  }
}

The following is the result of the aforementioned code:

Leave a Reply

Your email address will not be published.