Java Comments

We add comments in Java program for documentation and to increase readability of a program. It is a good programming practice to add comments in your code explaining the logic.

Comments in java are ignored by java compiler and interpreter. We can add comments anywhere and any number of times in our java program.

Types of Comments in Java

Java supports three kinds of comments:

  • Single Line Comments.
  • Multi Line Comments.
  • Documentation Comments.

Single Line Comments

  • Single line comment starts with “//” symbol and till end of the line.
  • It is used to comment only one line.
  • Everything on the line after // is ignored by compiler.
Foe Example:
// A method to calculate area of circle 
or
int sum; // Variable to store total marks
package com.tcc.java.tutorial;

public class HelloWorld{  
    public static void main(String args[]){ 
        // prints Hello World
        System.out.println("Hello World");  
    }  
} 
Output
Hello World

Multi Line Comments

  • Multi line comments in Java start with /* and end with */. Everything between /* and */ is ignored by compiler.
  • Multi line comment is used to add a comment spanning more than one line.
  • Nesting of multi-line comments is not allowed.
For Example:
/*
This method takes radius of a circle as input 
argument and returns the area of circle
*/
package com.tcc.java.tutorial;

/*
 First Java program to print "Hello World"
 String on screen
 */
public class HelloWorld{  
    public static void main(String args[]){ 
        System.out.println("Hello World");  
    }  
} 
Output
Hello World

Documentation Comment in Java

  • Java documentation comment starts with /** and ends with */.
  • It is used by JDK javadoc to automatically generate documentation.
  • Java doc is a tool in JDK, it automatically generates documentation in HTML format by parsing documentation comment in java code.
  • Javadoc recognize varius tags like @author, @param, @return etc.
For Example :
/**
* This method takes radius of a circle as input 
* argument and returns the area of circle
* @author John
*/
package com.tcc.java.tutorial;

/**
* First Java program to print "Hello World"
* @author John
*/
public class HelloWorld{  
    public static void main(String args[]){ 
        System.out.println("Hello World");  
    }  
} 
Output
Hello World