How to write multi-line comments in Java

In this article, you will learn how to comment multiple lines in Java.

Multi-line comments in Java

We are familiar with single-line comments in Java that start with two forward slashes ( // ). As long as the comment has only one line // works best. But if we have to write a paragraph describing something in the program then using // is not practical. It will be a hassle to precede every line of the para with //.

For example,

import java.util.*;
class multiLine{
  // comment line 1
  // comment line 2
  // comment line 3
  // comment line 4 
  
  public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a four-digit number:");
    int n1 = sc.nextInt();
    System.out.println("Enter the divisor:");
    int d = sc.nextInt();
  }
}

The four comment lines precede with //, which is time-consuming. Instead, we can use multi-line comments.

In Java, multi-line comments have an opening and a closing. They start /* and end with */ symbols. Anything we write between /* and */ will be a comment and, the program will not execute it.

Let’s see how we can write the same example above using multi-line comment symbols.

import java.util.*;
class multiLine{
  /* comment line 1
     comment line 2
     comment line 3
     comment line 4 */
  public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a four-digit number:");
    int n1 = sc.nextInt();
    System.out.println("Enter the divisor:");
    int d = sc.nextInt();
  }
}

Using /* and */ is easier than using // for multiple lines.

Multi-line comments also come in handy if you don’t want to execute some part of the code and save it for later use. You just need to surround that part with /* and */ and, you are good to go.

Also read: Guess The Number Game Using Java with Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *