Java Comments

COMMENTS IN JAVA

The purpose of including Java Comments in your code is to explain what the code is doing.

Java supports both single and multi-line comments. All characters that appear within a comment are ignored by the Java compiler.


Types of Java Comments:

There are three types of comments in Java.

i)Single Line Comment:

A single-line comment starts with two forward slashes and continues until it reaches the end of the line.

Syntax :

//This is single line comment

Example:

public class CommentExample1 {
public static void main(String[] args) {
    int i=10;//Here, i is a variable
    System.out.println(i);
}
}
     //Output :10

ii)Multi Line Comment:

Java also supports comments that span multiple lines.

You start this type of comment with a forward slash followed by an asterisk, and end it with an asterisk followed by a forward slash.

Syntax :

/*
This
is
multi line
comment
*/

Example:

public class CommentExample2 {
public static void main(String[] args) {
/* Let’s declare and
 print variable in java. */
    int i=10;
    System.out.println(i);
}
}
    //output:10

iii)Documentation Comment:

Documentation comments are special comments that have the appearance of multi-line comments, with the difference being that they generate external documentation of your source code. These begin with a forward slash followed by two asterisks, and end with an asterisk followed by a forward slash.

Syntax :

/**
This
is
documentation
comment
*/

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}

Spread the love

Leave a Comment

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