Different types of Comments in Java Programming

In Java programming, a comment is a piece of code that is not compiled by the compiler. Comments are the portion of the program intended for you and your fellow programmers to understand the code. In simple words, a description of the basic programming element is called comments. There are different types of comments in Java.

Comments are totally ignored by Java compilers. The compiler will not generate bytecodes for these comments. So, comments do not appear in the .class file.

Java supports two types of comments:-

  1. Implementation comments ( // and /* … */ )
  2. Documentation comments ( /* */ )

Implementation comments

The implementation comments are used for comments about the particular implementation. In Java the program can have four different types of implementation comments, those are:-

  1. Block comment
  2. Single line comment
  3. Trailing comments
  4. End-Of-Line comments

Block comment

For providing the description of methods, files, data structures, and algorithms the block comments are used. The block comment can be placed at the beginning of the file, before the method, within a method.

The block comment should be pretended by a blank line to set it apart from the rest of the code.

/*
 * It is an example of block comment.
 */ 

If the block comments are used inside the method then they should be indented to the same level as the code they describe.

void sample() {

     /*
      * It is an example of block comment.
      */
     if(condition) {

         /*
          * The comments inside method should be indented
          * to the same level as the code.
          */
     }
 }

Single line comment

The single-line comments are used for short comments. It appears on a single line indented to the level of the code that follows.

/* This is an example of single line comment */

The single-line comment should be preceded by a blank line. If we are not able to write a comment within a line then we should use block comment instead of a single-line comment.

void sample() {

     /* It is an example of block comment. */
     if(condition) {

         /* comment for the condition */
     } 
 }

Trailing comments

It can be used for very short comments. It can be placed on the same line as the code they describe but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.

 if(a==0) {
     return 0;   /* special case */
 } else {
     return 1;   /* for postive & negative value of a */
 }

End-Of-Line comments

The end of line comment (//) can be used in three places.

  1. In place of a single-line comment
  2. At the partial line (end-of-line)
  3. Consecutive multiple lines for commenting out sections of code

It should not be used on consecutive multiple lines for text comments. But, it can be used in consecutive multiple lines for commenting out sections of code.

void sample(int a, int b) {

   // It is an example of comment
   if( a<0 || b <0 ) {
       return false; //comment
   }
   else return a+b;

   // if( a<0 && b == 0 ){
   //  return 0;
   // } else {
   //  return 1;
   // }

 }

Documentation comments

Documentation comments are used for describing the specification of the code, from an implementation-free perspective. We must use document comments for providing the description to programming elements like classes, interfaces, constructors, methods, and fields. The documentation comment should be placed just before the declaration of programming elements.

The documentation comment can be extracted to HTML files using the Javadoc tool.


Javadoc comments example

//This program multiply two numbers
//Multiplication.java

/**
 * Multiplication of two number
 * The Multiplication program implements
 * an application that multiply the two
 * integer numbers and display the output
 * on the screen.
 *
 * @author     Rocco Jerry
 * @version    1.0
 * @since      2019-12-26
 */
public class Multiplication{

      /** This method is used to find
       * the multiplication of two number.
       * @param number1 first parameter of multiply method
       * @param number2 second parameter of multiply method
       * @return int It returns result value
       */
      public static int multiply(int number1, int number2){
             return number1 * number2;
      }

      /**
       * This is main method which make use
       * of multiply method.
       * @param args unused
       */
      public static void main(String[] args) {
              int num1 = 10;
              int num2 = 20;
              int result = multiply(num1, num2);
              System.out.println(num1 + " * " + num2 +" = " + result);
      }
 } 

Doc comments should not be positioned inside a method or constructor definition block, because Java associates documentation comments with the first declaration after the comment.

Tags

There are many tags are available for documentation comments. Some important and most of the time used tags are given below. They are given in the order, which should be followed for doc comment.

The tags should be Include in the following order:-

  • @author (classes and interfaces only, required):- It describes the author of the class. It’s syntax @author name-text
  • @version (classes and interfaces only, required):- It adds a “Version” subheading with the specified version-text to the generated docs when the -version option is used. The syntax is @version version-text
  • @param (methods and constructors only):- It adds a parameter with the specified parameter-name followed by the specified description to the “Parameters” section. The syntax is @param parameter-name description
  • @return (methods only):- It adds a “Returns” section with the description text. The syntax is @return description
  • @exception:- @throws is a synonym added in Javadoc 1.2, the syntax is @throws class-name description
  • @see:- It adds a “See Also” heading with a link or text entry that points to reference. It’s syntax @see reference
  • @since:- It adds a “Since” heading with the specified since-text to the generated documentation. The syntax is @since release
  • @serial (or @serialField or @serialData)
  • @deprecated:- It adds a comment indicating that this API should no longer be used. The syntax is @deprecated deprecated-text

Generating doc file

We can generate doc file above program Multiplication.java. For generating a doc file from a Java file we will use the command Javadoc. Like javac and java commands, Javadoc is also a java tool. It is used for generating a documentation file (an HTML file). The Javadoc is also available in the jdk\bin folder.

The Javadoc tool also displays the error message if there is an error that occurred in doc comment.

>  javac Multiplication.java
>  javadoc Multiplication.java
types of comments in java

There are many files are generated using the Javadoc tool. Now, open Multiplication.html file, you will see all documentation of Multiplication class.

We got an enhancement on API doc file generation in the Java9 version. From the Java9 onwards, for API doc file generation purpose the Oracle corporation is using HTML5 and jQuery and they provided the search option in API doc file to find any class easily.


When we should use Implementation comments and doc comments?

After generating the API doc file using the Javadoc tool, the documentation comment will be present in the API doc file.

We must not use Implementation comments for providing the description to a programming element. If we use it then there will be no compile-time error, but that description will not be present on the API doc file. Hence, to provide a description of the programming element we must use only the documentation comment.

Similarly, we must not use documentation comments for the particular implementation. Here also no compile-time error occurs, but those comments will be available on the doc file.

If we need to give information about programming elements that are not related to the documentation then we should use a single line comment or block comment immediately after the declaration.


We can place comments anywhere in Java files. We can place comments directly in Java file, inside a class and, inside a method, and even we can place comments inside a class/method/variable name but with care.

Where comments can be placed in Java

Compiler work for different types of comments in Java

// :- Compiler reads and ignores every character after // up to the newline. When newline cames then the compiler starts its own work.

/* … */ :- Compiler reads and ignores every character after /* and when */ cames then it stop ignoring and start compiling the statements of java program.

/** … */ :- The statements inside /** … */ placed in the java API doc file using the Javadoc tool. The compiler ignores all the statements from /** to */


Error based on invalid Comments

We can get four types of error based on invalid comments.

  • When an invalid comment is placed directly in Java file then error: class, interface, or enum expected
  • If an invalid comment is inside the class then the error: illegal start of type
  • When an invalid comment is inside the method then we got the error: illegal start of expression
  • If the comment is inside the method and unclosed then error: unclosed comment
invalid comments in Java
error based on invalid comments in java

Note there is an exceptional case with the Unicode character set. We know that any text, words, and characters can be written as a comment, but there is a different case for the Unicode character set.

We can’t place wrong Unicode literal even inside a comment. The compiler will keep throwing an error until we remove this wrong literal or correct this literal.

class A{
    public static void main(String[] args) {
      System.out.println("\u0041");
      //This is comment \u00GG
    }
 }
wrong comment as unicode character set

Use Comments in the right way

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.

Discussion of nontrivial or non-obvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.

The frequency of comments sometimes reflects the poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Comments should not be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace.


For detail knowledge of the doc comment learn:-

How to write Doc comments for the Javadoc Tool
Javadoc FAQ
Comments


Question) Find out the valid and invalid comments from the below list

If Java compiler throws compilation time error then those comments are invalid.

 1. //
 2. /////////////////////
 3. // /*
 4. /*
 5. /* */
 6. /* // */
 7. // /* // */
 8. /* /*       */
 9. /*    */         */
 10. ///*     */       */
 11. /*   /*       */       */
 12. /*   /*       *  /       */ 

Valid Comments for Java are :- 1,2,3,5,6,7,8,10,12

Invalid Comments are:- 4, 9 and 11

For 12, closely look there is space between third * and /. So, it is not consider as comment.


If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

2 thoughts on “Different types of Comments in Java Programming”

Leave a Reply