JavaJava Comments

Java Comments

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Tutorials

I have worked with developers who espoused the notion of “self-documenting code”. This is the misguided idea that well-written code should not require comments. Hogwash! While we should all strive to make our code as readable and understandable as possible, comments remain a vital coding best practice. The reason is simple: while well-written code is easier to follow, it still does not provide any insight into why something is being done a certain way. Having said that, it is easy to overdo it on comments, or write comments that do not add much useful information. This programming tutorial will present the different kinds of comments in Java, as well as provide some guidelines on how to make the best use of them.

Looking to learn Java in a course or online training environment? We have a list of the Top Online Training Courses for Java Programming to help get you started.

How to Comment in Java

In computer programming, comments are lines of code that are completely ignored by the compiler. As such, their purpose is to help programmers understand the code and its context, beyond typical best practices, such as proper variable naming, breaking complex operations into multiple lines, and so forth.

The key takeaway here is that comments should shed light on the developer’s intentions and not provide a play-by-play of each and every line of code! To illustrate, here are some redundant single-line comments that really do not add anything to the proceedings:

// declare and initialize two variables
String name = "Rob";
int    age  = 53;

// print the output
System.out.println("Hi, I'm " + name + " and I'm " + age + " years young.");

In the above code example, a developer should be able to easily understand that the String name” and int age” are both being declared and initialized, and therefore, adding a comment to explain the code, in this case, is redundant and only clutters up the code. Likewise, any Java developer seeing the println() function should know what the function does, and, again, writing a comment explaining it is just repetitive.

The comment below states what the function does, even though its name should probably suffice:

// This method is used to find average of three numbers. 
public int average(int numX, int numY, int numZ)  
{ 
  return (numX + numY + numZ)/3; 
} 

Now here is a specialized file parsing method in which some configuration is being set. In this case, a comment explains WHY the default type is being set:

public static void parseFilesForFolder(final File folder) {
  HapiContext context = new DefaultHapiContext();
  
  // Setting the following property allows you to specify a default
  // value to assume if OBX-2 field is missing.
  context.getParserConfiguration().setDefaultObx2Type("ST");
  
  // ...
}

Read: Java Primitive Data Types

Types of Comments in Java

Java supports three types of comments:

  • Single-line comments
  • Multi-line comments
  • Documentation comments

Single-line Comments in Java

As the name suggests, these comments consist of a single line. They begin with two forward slashes (//):

// this is a single-line comment in Java

They can also be used to make in-line comments:

public class Main {
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++){ // outer for loop
      for (int j = 0; j < 10; j+=2){  // second for loop
        for (int k = j; k < 20; k++){  // inner most for loop
          System.out.println("k = " + k);
        }
      }
    }
  }
}

Multi-line Comments in Java

Although you can create multi-line comments by adding “//” at the beginning of each line, this can become quite tedious when comments span more than a line or two. In those cases, you should consider wrapping them in “/*” and “*/” like so:

/* this is a multi-line
comment in Java
that spans multiple
lines... */	

Developers often see multi-line comments formatted as follows:

/*
 * This method calculates the average of three integers.
 * @param num1 This is the first parameter to getAvg method
 * @param num2  This is the second parameter to getAvg method
 * @param num3  This is the second parameter to getAvg method
 * @return int This returns average of num1, num2 and num3.
 */
public int getAvg(int num1, int num2, int num3)
{
  return (num1 + num2 + num3) / 3;
}

Although the asterisks (*) at the start of each line do not do anything, they make the comments more obvious and easy to read.

Documentation Comments

Documentation comments come into play when code is written for a project or a software package. Certain utilities such as the JDK Javadoc tool can generate a documentation page for reference from the documentation comments, which provides information about methods, parameters, and more.

Documentation comments are very similar to regular multi-line comments except that the starting characters include an extra asterisk: “/**“. Here is an example of how to create a documentation comment in Java:

/**Documentation comment begins here. ***********
*
*Specialized tags are employed in order to specify a parameter,
*method or return value.
*HTML tags can also be utilized
*such as <p> or <strong></strong>
*
*Comment ends here. *****************************
*/	

Read: Java Output Basics

Javadoc Tags

Tools like Javadoc accept a variety of standard tags. Here are a few of them:

Tag Syntax Description
{@docRoot} {@docRoot} To depict relative path to root directory of generated document from any page.
@author @author name – text To add the author of the class.
@code {@code text} To show the text in code font without interpreting it as html markup or nested javadoc tag.
@version @version version-text To specify “Version” subheading and version-text when -version option is used.
@since @since release To add “Since” heading with since text to generated documentation.
@param @param parameter-name description To add a parameter with given name and description to ‘Parameters’ section.
@return @return description Required for every method that returns something (except void)

The comments for the getAvg() method above could easily be adapted for documentation by adding the extra asterisk at the beginning:

/**
 * This method calculates the average of three integers.
 * @param num1 This is the first parameter to getAvg method
 * @param num2  This is the second parameter to getAvg method
 * @param num3  This is the second parameter to getAvg method
 * @return int This returns average of num1, num2 and num3.
 */
public int getAvg(int num1, int num2, int num3)
{
  return (num1 + num2 + num3) / 3;
}

Final Thoughts on Java Comments

In this programming tutorial, we learned about the three types of comments in Java, as well as how to make the best use of them. Remember, programmers do not need to comment every line, just those whose purpose may not be readily inferred. Even if you are the only coder who works with a project, you would be amazed how quickly you can forget why you did something a certain way or how you intended a block of code to work.

Read more Java programming and software development tutorials.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories