Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.
  • Single Line Comment
  • Multi Line Comment
  • Documentation Comment
  • Single Line Comment

    The single line comment is used to comment only one line.

    syntax:

    //This is single line comment

    Example

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

    Output

    12

    Multi Line Comment

    The multi line comment is used to comment multiple lines of code.

    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=12;  
    System.out.println(i);  
     }  
     }  
    

    Output

    12

    Documentation Comment

    The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool.

    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 r, int s){return r+s;}  
     /** The sub() method returns subtraction of given numbers.*/  
    public static int sub(int r, int s){returnr-s;}  
     }   
    

    Compile it by javac tool:

    javac Calculator.java

    Create Documentation API by javadoc tool:

    javadoc Calculator.java
    Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML files and see the explanation of Calculator class provided through documentation comment.