, ,

Comments – Basic Elements, Primitive Data Types, and Operators

Comments

A program can be documented by inserting comments at relevant places in the source code. These comments are for documentation purposes only and are ignored by the compiler.

Java provides three types of comments that can be used to document a program:

  • A single-line comment: // … to the end of the line
  • A multiple-line comment: /* … */
  • A documentation (Javadoc) comment: /** … */’
Single-Line Comment

All characters after the comment-start sequence // through to the end of the line constitute a single-line comment.

Click here to view code image

// This comment ends at the end of this line.
int age;        // From comment-start sequence to the end of the line is a comment.

Multiple-Line Comment

A multiple-line comment, as the name suggests, can span several lines. Such a comment starts with the sequence /* and ends with the sequence */.

/* A comment
   on several
   lines.
*/

The comment-start sequences (//, /*, /**) are not treated differently from other characters when occurring within comments, so they are ignored. This means that trying to nest multiple-line comments will result in a compile-time error:

Click here to view code image

/* Formula for alchemy.
   gold = wizard.makeGold(stone);
   /* But it only works on Sundays. */
*/

The second occurrence of the comment-start sequence /* is ignored. The last occurrence of the sequence */ in the code is now unmatched, resulting in a syntax error.

Documentation Comment

A documentation comment is a special-purpose multiple-line comment that is used by the javadoc tool to generate HTML documentation for the program. Documentation comments are usually placed in front of classes, interfaces, methods, and field definitions. Special tags can be used inside a documentation comment to provide more specific information. Such a comment starts with the sequence /** and ends with the sequence */:

Click here to view code image

/**
 *  This class implements a gizmo.
 *  @author K.A.M.
 *  @version 4.0
 */

For details on the javadoc tool, see the tools documentation provided by the JDK.

Related Posts