Three Types of Comments in Java: Javadoc, Single-line and Multi-line

Single-line, Multi-line and Java-doc Comments in Java Code

Java language provides three styles (Single Line, Multi-line, and Javadoc) of comments. Before talking of a particular Java comment type we should know that a Java comment can be inserted anywhere in a program code where a white space can be. Java compiler does not include them in final executable. So, you can insert as many Java comments as you want until they are proven to be useful. Following three styles of comments Java supports.

  1. Java single line comments or slash-slash comments or end of the line comments (//...)
  2. Java multi-line or traditional comments (/*...*/)
  3. Javadoc or Java documentation comments (/**...*/)

Java's single line and multi-line comments are collectively called implementation comments, while Javadoc comments are called documentation comments. Implementation comments are used for internal documentation. To internally document a program non-executable human-readable implementation comments are inserted. These comments should be used to give overviews of code and provide additional information that is not readily available in the code itself.

On the other hand Javadoc comments too inserted into the source code but they are read by a special javadoc tool in order to generate source code documentation.

Java Single Line Comments or Slash-slash Comments

Java's single line comment starts with two forward slashes with no white spaces (//) and lasts till the end of line. If the comment exceeds one line then put two more consecutive slashes on next line and continue the comment.

Java's single line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. And sometimes to comment out one or more lines of code. Java single line comments are usually not used on consecutive multiple lines for text comments. See the following piece of code demonstrating single line comment

if(x < y) 
{ // begin if block
    x = y;
    y = 0;
} // end if block

Java Multi-Line Comments or Slash-star Comments

Java's multi-line or slash-star or traditional comment is a piece of text enclosed in slash-star (/*) and star-slash (*/). Again there should be no white space between slash and star. Java's multi-line comments are useful when the comment text does not fit into one line; therefore needs to span across lines. Slash-star comments are the only choice when a comment needs to be inserted in middle of the code line. For example:

// CommentDemo.java
// Demonstrating multi-line comments
public class CommentDemo
{
  public static void main(String[] args)
  {
      for (int i = 0; i < 5; /* exits when i reaches to 5 */ i++)
      {
          System.out.print(i + " ");
      }
  }
}
OUTPUT
======
0 1 2 3 4 

In CommentDemo.java a comment is inserted in for loop header. If we need to supply a comment somewhere in middle of the code line, then we are left with the only choice of slash-star comment.

It is very important to keep following points in mind, while inserting comments in a Java programs.

  1. Comments should not be nested, especially slash star comments
  2. Comments surrounded by double quotes are processed as string literals
  3. Nesting of slash-star (/* and */) comments have no special meaning in double slash (//) or single line comments.
  4. Nesting of double slash (//) comments has no special meaning in slash-star (/*) comments or Javadoc (/**) comments.
  5. Be aware of Unicode characters in Java comments

1. Java Comments should not be nested, especially slash star comments

Java's slash-star comments end with closing star-slash (*/). So as soon as a closing */ is encountered the comment should be considered ended. If you try to nest a slash-star comment then wherever the */ of inner comment is encountered the whole comment will be treated finished, and rest of the text will be assumed usual Java code that will result into compile time error. As an example, below piece of comment code is not correct:

/* This comment contains /* nested comment. */ 
 * The comment ends where the first star-slash (*/) 
 * occurs. Rest of the text after the first 
 * star-slash is treated as usual Java code.
 */

Nesting of single line or slash-slash (//) comments would not result into compile time errors, because a single line comment automatically gets ended with the line.

2. Comments surrounded by double quotes are processed as string literals

If a Java comment is surrounded by double quotes, it is processed as a string literal instead of a comment by the Java compiler. For example, the following declarations of String commS, and String commS1 contain comment like strings but these are not treated as valid Java comments and get printed as it is if printed by System.out.println().

/* CommentDemo.java
 * Java comments surrounded by double quotes are processed
 * as string literals instead of a comment by the Java compiler.
 */
public class CommentDemo
{
  public static void main(String[] args)
  {
    String commS = "/* It looks like a comment but It is treated as string */";
    String commS1 = "// It too look like a comment but It is treated as string";
 
    System.out.println(commS);
    System.out.println(commS1);
  }
}
OUTPUT
======
/* It looks like a comment but It is treated as string */
// It too look like a comment but It is treated as string

3. Nesting of slash-star (/* and */) comments have no special meaning in double slash (//) or single line comments.

Java's slash-star (/* and */) comments when nested in double slash (//) have no special meaning and get ended with the current line. In real life programming you should not do that nesting because it is confusing and serve no purpose.

4. Nesting of double slash (//) comments has no special meaning in slash-star (/*) comments or javadoc (/**) comments.

Vice versa Java's double slash (//) comments nested in slash-star (/*) comments or javadoc (/**) comments have no special meaning but create confusion. You must avoid doing that.

5. Be aware of Unicode characters in Java comments

Java programs interpret Unicode characters as usual tokens even in comments because Unicode sequence is processed early in the Java compiler's lexical scanning of the source file, even before comments are processed. So at compile time during code scanning, wherever a Unicode presenting a character appears it is recognized as usual Java token. For example, Unicode for character * is \u002a and for / is \u002f; therefore you can write a comment as /* comment is ended by using Unicode characters \u002a\u002f. Here, Java compiler will recognize \u002a as *, and \u002f as / and the compiler will treat it a right comment. Here goes an example.

/* UnicodeCommentDemo.java
 * Java programs are written using Unicode characters
 * Unicode presenting a character recognized as usual Java token
 */
 
public class UnicodeCommentDemo
{
   public static void main(String[] args)
   {
      double pi = Math.PI;
      /* multiplies pi by 4 \u002a\u002f
      // above comment is lexically equivalent to the following
      /* multiplies pi by 4 */
      System.out.println(pi \u002A 4); // \u002A is Unicode of *
   }
}
OUTPUT
======
12.566370614359172

The newline character, if supplied by its Unicode then you can write more than one statement on a single line as follows:

int x = 0; // x is zero \u000a x = 10; // now x is 10
System.out.println(x);

The above piece of code will be compiled successfully and print 10 on the screen. The Unicode \u000a supplies a new line to end the first comment.

Java Documentation (Javadoc) Comments

Java documentation (Javadoc) comments are written to document the APIs a class reveals to its users. Users of a class, of course, are programmers. API documentation is developed as part of the source code and kept in source files. By using Java documentation comments classes, fields, constructors and methods are documented.

Javadoc is a tool which comes as part of JDK. This tool generates html documentation from the source files. It parses the comments enclosed in /** and */ from .java source files and outputs html documentation comments in form of html pages. That's the reason comments surrounded by /** and */ are called Javadoc comments. Under this topic we will discuss how Javadoc comments are written, what guidelines should be followed while writing Javadoc comments, how to use javadoc tool to generate Java documentation comments, and how to see generated Javadoc comments.

Java documentation comments are written in html surrounded by /** and */ and like traditional comments can span multiple lines of code.

Where to Place Javadoc Comments in a Program

Java documentation (Javadoc) comment is placed just before the entity to be documented. As said before, it can be a class, field, constructor, or method. A documentation comment is formed of two parts -- a description followed by one or more Javadoc tags. Predefined Javadoc tags (whose names start with @) control the look of resultant HTML page. Let's take a small example to show how documentation comments are written. In mentioned example, Javadoc comments are in italic green.

// JavadocCommentDemo.java
/**
 * First sentence of the comment should be a summary sentence.
 * Documentation comment is written in HTML, so it can 
 * contain HTML tags as well. 
 * For example, below is a paragraph mark to separate 
 * description text from Javadoc tags.
 * <p/> 
 * @author Krishan Kumar
 */
 
public class JavadocCommentDemo
{
    /** main method
     * @param args String[]
     */
    public static void main(String[] args)
    {
        System.out.println(sqrt(16));
    }
 
    /**
     * computes sqrt of passed number of type double.
     * @param x double
     * @return sqrt of x
     */
    public static double sqrt (double x)
    {		
        return Math.sqrt(x);
    }
}

From the comments inserted in .java file HTML documentation is generated with help of javadoc tool. The javadoc is a tool that comes with JDK and used to generate HTML documentation pages. But, before trying javadoc tool to generate documentation pages we will see Javadoc tags that starts with @ symbol (for an instance, @author tag used in JavadocCommentDemo.java)

Javadoc Tags in Documentation comments

Javadoc tags follow the syntax @tag [tag description]. The <tag description> is an optional part, but the tag would have no worth if description is omitted. Table 1 explains most used tags concisely.

Table 1: Javadoc Tags
Tag >Syntax >Description
@author @author name @author tag is used in interface and class comments.
@since @since version @since tag is used in interface and class comments. It tells the version in which the class or interface first time introduced.
@version @version description @version tag is used in interface and class comments. It describes the current version number of the class or interface.
@deprecated @deprecated @deprecated tag is used in interface, class, and method comments. It is used to indicate that an item is a member of the deprecated API. Deprecated items should not be used. They are merely included for backward compatibility.
@param @param name description @param tag is used in method comments. It describes a method parameter. The name should be the formal parameter name. The description should be a brief one line description of the parameter.
@return @return description @return tag is used in method comments. It describe the return value from a method with the exception of void methods and constructors.
@throws @throws exception description @throws tag is used in method comments. It indicates any exceptions that the method might throw and possible reasons for the occurrence of this exception.
@see @see classname @see tag is used in interface, class, field, and method comments. This tag is used to give a link to another class if another class may help in providing more clarity.

In addition to above Javadoc tags listed in Table 1, there are a few more. Aforementioned are the most used ones.

Standard Order of Javadoc Tags

While documenting an interface, class, field, method or constructor Javadoc tags are included in the given order depending upon their applicability to the item.

  • @author (classes and interfaces only, required)
  • @version (classes and interfaces only, required.)
  • @param (methods and constructors only)
  • @return (methods only)
  • @exception (@throws is a synonym added in Javadoc 1.2)
  • @see additional information (mostly another class)
  • @since version number since the class exists
  • @serial (or @serialField or @serialData)
  • @deprecated should not be used, it's for backward compatibility

Generating Javadoc Comments

To generate Javadoc Comments in form of HTML documentation pages, the javadoc tool is run from the command line much like the Java compiler. This tool is invoked by supplying javadoc command along with required number of command line parameters. Following is the command line syntax of javadoc tool.

command-line# javadoc [options] [file list separated by spaces]

Here are some Javadoc options:

  • -author - Include @author paragraphs
  • -classpath <pathlist> - Specify where to find user .class files.
  • -d <directory> - Destination directory for output files.
  • -private - generated documentation will include private fields and methods (only public and protected ones are included by default).
  • -sourcepath <pathlist> - Specify where to find source files to generate documentation pages.
  • -version - generated documentation will include a version section

Suppose our example file JavadocCommentDemo.java is located on C:\ drive and to generate Javadoc documentation for that, we have to execute the following command.

C:\> javadoc -author JavadocCommentDemo.java

On successful execution of the above command you will get a JavadocCommentDemo.html page along with a few more html pages generated on C:\ drive.

Last Word

In this tutorial we talked of Java's single line, multi-line, and Javadoc comments. Single line, and multi-line comments are also called implementation comments, while Javadoc comments are called documentation comments. Java's single line comments are used for one lines explanation they are also called trailing or end-of-line comments. Multi-line comments or slash-star comments are called block comments. Java's block comments are used when more than one line of comments are written. Javadoc comments or documentation comments are inserted to describe classes, interfaces, fields, methods, or constructors. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.