Comments in Java

Comments in Java

Comments in Java are programmer-readable statements or annotations added in the program to make sense of what the code is about.

Why are Comments needed in a Java program?

Comments are vital and needed in a program for the following reasons:

    • Comments in a program make it highly readable and thus understandable.
    • Comments make it easy for the programmers to find errors in a program if any.

Types of Comments in Java

Comments are classified into three categories:

    • Single Line Comment

    • Multi Line Comment

    • Documentation Comment

Single Line Comments in Java

Single Line comment is used to comment only a single line of code. It starts with 2 forward slashes and whatever that follows is ignored by the compiler. It is the most common comment used by both the beginner and the advanced-level programmers.

Syntax of Single Line Comment in Java:

//This is a single line comment.

Example of Single Line Comments:

//Java program with single-line comment
public class SingleLineComment {
    public static void main(String[] args) {
        
        //variable of type int
        int var=3;

        //printing it
        System.out.println(var);
    }
}

Output:

3

 

 

Multi Line Comment in Java

Multi Line comment in Java is used to comment more than a single line of code which means a block lines. It starts with a forward slash followed by an asterisk and whatever that follows it is ignored by the compiler and then ends with an asterisk followed by a forward slash.

Syntax of Multi Line Comment in Java:

/* This is 
a multi line
comment */

Example of Multi Line Comments:

//Java program with a multi line comment
public class MultiLineComment {
    public static void main(String[] args) {
        /*variable declaration
        and initialization done is
        a single line*/
        int var=4;
        System.out.println(var);
    }
}

Output:

4

 

 

Documentation Comment in Java

Documentation comments in Java are usually used in large programs or software projects which require proper documentation API. These APIs are required for reference to know which classes, interfaces, methods are used in the code. It starts with a forward slash followed by two asterisks and whatever that follows it is ignored by the compiler and then ends with an asterisk followed by a forward slash. It spans more than one line like the multi-line comment.

Syntax of Documentation Comment in Java:

/**
This is a 
documentation comment
*/

 

Share this post

4 thoughts on “Comments in Java

  • 25/07/2022 at 5:21 pm
    Permalink

    It is very useful for the students thuse who are preparing

    Thanks & Regards,
    V.Saibabu.

    Reply
  • 23/09/2022 at 4:37 pm
    Permalink

    this is very useful content thanks for sharing

    Thanks & Regards
    V.saibabu

    Reply

Leave a Reply

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