How To Write Java Comments The Right Way

Commenting is an integral part of any programming language. Tt is a guide that helps in better understanding the functionality of a program. Good programmers tend to comment as they go while writing the code.

Most of the time, when you write code, you will need to go back and make changes later. Without Java comments, it’s easy to get lost.

This is why I specifically make sure to make comments as I write code. Not only does it help me keep track of the code as it grows more complicated, but it also makes the code more understandable for anyone that needs to reference the code at a later date.

Comments in Java are the statements in the Java code that are not executed when the program is run. Think of them as markers that guide the reader.

Said differently, comments provide information about the code without changing the code’s functionality. Some programmers can also use it to disable certain portions of code during development.

In this tutorial, I will how to write Java comments and what are some of the best ways to use them.

Table of Contents

You can skip to a specific section of this tutorial on how to write Java comments using the table of contents below:

Types of Comments in Java

In Java, the role of comments is to make it more human readable. Comments can make finding errors in Java program easier. Here are different types of comments in Java:

1. Single-line Comments

As the name suggests, these comments end in single line. They begin with two forward slashes (//). They can also be used to make in-line comments.

Syntax:

// this is a single-line comment in Java

Example:

//my first comment
public class HelloWorld {
  public static void main(String[] args) {
   System.out.println("Hello World!");
  }
}

Output:

Hello World!

2. Multi-line Comments

When a comment has to be longer than one line, multi-line comments are useful. Multi-line comments can also be created by putting ‘//’ at the beginning of each line, but that becomes quite tedious when comments are very long.

To avoid this, it’s better to wrap multi-line comments in Java in ‘/*’ and ‘*/’.

Syntax:

/* this is a multi-line
comment in Java
and it continues up to
here */	

Example:

/* This is the beginning of a
multi-line comment
this is the end for Hello World Program */
public class HelloWorld {
  public static void main(String[] args) {
   System.out.println("Hello World!");
  }
}

Output:

Hello World!

3. Documentation Comments

Documentation comments are used when code is written for a project or a software package. Documentation comments help generate a documentation page for reference, which is useful in getting information about methods, parameters and more. The JDK Javadoc tool makes the use of documentation comments.

Documentation comments are wrapped in ‘/**’ and ‘*/’.

Syntax:

/**Documentation Comment begins here
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends here*/	

Javadoc is a tool that comes with JDK and is used for generating Java code documentation in HTML from java source code. Here is the table of tags that can be used in Java:

TAG DESCRIPTION SYNTAX    
@author This tag adds the author of a class. @author name-text    
{@code} This tag displays text in code font without interpreting the text as HTML markup or nested javadoc tags. {@code text}    
{@docRoot} This tag represents the relative path to the generated document’s root directory from any generated page. {@docRoot}    
@deprecated This tag adds a comment indicating that this API should no longer be used. @deprecated deprecatedtext    
@exception This tag adds a Throws subheading to the generated documentation, with the classname and description text. @exception class-name description    
{@inheritDoc} This tag inherits a comment from the nearest inheritable class or implementable interface. Inherits a comment from the immediate surperclass.    
{@link} This tag inserts an in-line link with the visible text label that points to the documentation for the specified package, class, or member name of a referenced class. {@link package.class#member label}    
{@linkplain} This tag identical to {@link}, except the link’s label is displayed in plain text than code font. {@linkplain package.class#member label}    
@param This tag adds a parameter with the specified parameter-name followed by the specified description to the “Parameters” section. @param parameter-name description    
@return This tag adds a “Returns” section with the description text. @return description    
@see This tag adds a “See Also” heading with a link or text entry that points to reference. @see reference    
@serial This tag is used in the doc comment for a default serializable field. @serial field-description include exclude
@serialData This tag documents the data written by the writeObject( ) or writeExternal( ) methods. @serialData data-description    
@serialField This tag documents an ObjectStreamField component. @serialField field-name field-type field-description    
@since This tag adds a “Since” heading with the specified since-text to the generated documentation. @since release    
@throws The @throws and @exception tags are synonyms. @throws class-name description    
{@value} When {@value} is used in the doc comment of a static field, it displays the value of that constant. {@value package.class#field}    
@version This tag adds a “Version” subheading with the specified version-text to the generated docs when the -version option is used. @version version-text    

Example:


//Java program to illustrate frequently used  
// Comment tags or Documentation comments
  
/** 
* <h1>Program to find average of three numbers!</h1> 
* The FindAvg program implements an application that 
* simply calculates average of three integers and Prints 
* the output on the screen. 
* 
* @author Nick McCullum 
* 
*/
public class FindAvg  
{ 
    /** 
    * This method is used to find average of three numbers. 
    * @param numX This is the first parameter 
    * @param numY  This is the second parameter 
    * @param numZ  This is the second parameter to 
    * @return int This returns average of numA, numB and numC. 
    */
    public int findAvg(int numX, int numY, int numZ)  
    { 
        return (numX + numY + numZ)/3; 
    } 
  
    /** 
    * This is the main method which makes use of findAvg method. 
    * @param args Unused. 
    * @return Nothing. 
    */
  
    public static void main(String args[])  
    { 
        FindAvg obj = new FindAvg(); 
        int avg = obj.findAvg(30, 60, 90); 
  
        System.out.println("Average of 30, 60 and 90 is : " + avg); 
    } 
}

Output:

Average of 30, 60 and 90 is : 60

The documentation for the above given code can be generated using a ‘javadoc’ tool by running the following command:

javadoc FindAvg.java

More Ways of Using Java Comments

1. Nested Single-line Comments

A single-line comment that is written inside a block of code is called a nested single-line comment.

Nesting is a term that refers to placing of a comment or an additional block of code inside another block of code - which could be a function, a loop, or something else. The compiler will skip the comment and continue to process the rest of the code.

public class HelloWorld {
  //this is illustration of a nested comment
  public static void main(String[] args) {
   System.out.println("Hello World!");
  }
}

2. Nested Multi-line Comments

A multi-line comment placed inside a block of code is called a nested multi-line code. An example is below:

public class HelloWorld {
  /* This is an example of a nested
multi-line comment in java */
  public static void main(String[] args) {
   System.out.println("Hello World!");
  }
}

3. Single-line Comments Nested Inside Multi-line Comments

In certain cases, it may be useful to place a single-line comment inside of a multi-line comment.

An example is below:

public class HelloWorld {
  /* This is the beginning
  of a multi-line comment
  // This is a nested single line comment
   this is the end of the entire comment */
  public static void main(String[] args) {
   System.out.println("Hello World!");
  }
}

However, a multi-line comment cannot be nested inside another multi-line comment.

Best Practices for Writing Java Comments

I wanted to close this tutorial with some best practices for writing Java comments:

  1. Remember that comments are not subtitles and therefore, your comments shouldn’t translate each line of code into human language. Said differently, comments are supposed to support the code so that when you or anybody comes back to it, they can make sense of it. Explaining the code in detail will only look silly and also make your code bulky.
  2. Do not just repeat what you code is able to explain clearly. There are certain commands that are clear enough and do not need explanation. As an example, the following comment is unecessary:
    System.out.println("Hello World!"); //prints Hello World! to //console.
    

    To reiterate, the above code is simple and clear. The comment in it is redundant and not required.

  3. Smelly comments need to be avoided at all cost. When you try to explain a code in detail to make sure the reader is not confused, it’s a signal that something is wrong with your code. No comment can fix that.
  4. Write your comments as you go and do not make it a habit of going back and commenting after code completion.
  5. Keep the comments short and precise.
  6. When you place comments inline, make sure they are separated from the main code with at least two spaces.

Final Thoughts

An important characteristic of good code is how concise and comprehendible it is.

In this tutorial, you learned how to write readable and meaningful Java comments. By commenting your code properly during the development stage using the tools discussed in this tutorial, your code will become more useful and valuable both for yourself and any other developers who work on it later.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:
Written on May 16, 2020