Comments in Java

Any software would be incomplete without comments. They aid the person viewing the code (usually you) in comprehending the program’s aim and functionality. You must develop the practice of always commenting on your code as you write it rather than afterward.

The tools we’ll use in this article will remind you to write comments, assist you in writing them, and exploit the comments you’ve written to make programming easier. Please make use of them.

Types of Comments in Java

There are four to five types of comments in Java, depending on how you look. These include:

Documentation and implementation comments

Documentation comments and implementation comments are the two sorts of comments that should occur in programs. The class’s, field’s, or method’s semantics are described in documentation comments.

You should be able to utilize the class and its methods without reading any source code if the documentation comments are good. On the other hand, implementation comments explain how a piece of code works. While you should write implementation comments as needed, documentation comments are an essential programming component and are required here.

The other types of comments in Java include:

Comments on a single line

Two forward slashes (//) begin single-line comments. Java ignores any text between // and the end of the line (will not be executed). Before each line of code, a single-line comment is used:

// This is a comment
System.out.println("Single line comments in Java");

A single-line comment is used at the end of a line of code in the following example:

System.out.println("Single Line Comments at the end of the line"); // This is a comment

Multi-line comments in Java

Comments that span multiple lines begin with /* and conclude with */. Java will ignore any text between /* and */. To clarify the code, this example uses a multi-line remark (a comment block):

/* The output of the code below is the words Hello multi-line comments in Java

to the screen, and it is code magic */

System.out.println("Hello multi-line comments in java");

Do you want single-line or multi-line comments?

It is entirely up to you which method you wish to employ.// is used for short comments, and /* */ is used for longer ones.

What are the benefits of using comments in code?

  • Comments add details to the code to make the program more legible.
  • It makes it simple to maintain the code and locate errors.
  • The comments provide more information or explanations about a variable, method, class, or sentence.
  • It can also prevent program code execution while evaluating alternative code.

Java documentation Comments

Documentation comments are commonly used to help construct documentation API when writing massive programs for a project or software application. These APIs are required for reference to determine which classes, methods, arguments, and other elements are used in the code.

The Javadoc tool is required to develop documentation API. Between /** and */ are the documentation comments.

The syntax is as follows:

*several tags to depict the parameter
*or heading or author-name
*We can also use HTML tags   

Tags for Javadoc

Tags that are frequently used in documentation comments include:

{@docRoot}{@docRoot}depicts the relative path to the root directory of the resultant document generated from any page.
@author@author namethe text adds the class’s author.
@code{@code text}shows the text in code font though it does not interpret it as either nested javadoc tag or html markup.
@version@versionversion-text specifies the “Version” subheading and the version-text when using the version option.
@since@sincethe release adds the “Since” heading with since text to the resultant documentation generated.
@param@paramthe parameter-name description adds a parameter with a name and description to the section dubbed ‘Parameters’.
@return@returndescription It is needed for every method that returns something except void.

The section below allows us to use the Javadoc tag in a Java program.

     * <h2> Number Calculation </h2>
     * This program is an application implemention
     * to perform operation such as addition of numbers  
     * and print the result  
     * <p>
     * <b>Note:</b> Comments are responsible for making the code readable and  
     * easy to understand.
     * @author Codeunderscored  
     * @version 16.0
     * @since 2022-03-19
     public class CodeCalculation{  
         * The code in this method here sums two integers.
         * @param input1 This is the first parameter to sum() method
         * @param input2 This is the second parameter to the sum() method.
         * @return int This returns the addition of input1 and input2
        public int sum(int input1, int input2){  
            return input1 + input2;  
        * This is the primary method uses of sum() method.
        * @param args Unused
        * @see IOException  
        public static void main(String[] args) {  
            Calculate obj = new Calculate();  
            int result = obj.sum(25, 35);  
            System.out.println("Number summation: " + result);  

The HTML files for the Calculate class are now created in the current directory, abcDemo. We can see the documentation remark explaining the Calculate class when we open the HTML files.


Documentation comments in Java are set inside the comment delimiters /**… */ by convention, with one comment per class, interface, or member. Each comment line should begin with a “*” and should occur directly before the class, interface, or member declaration.

Here’s a crazy class that shows how to format your comments (not how to write Java code):


 * The Codeunderscored class is an example to illustrate documentation
 * comments.
public class Codeunderscored {

    * integer keeps track of for fun.
    private int count;


    * Increment a value by delta and return the new value.
    * @param  delta   the amount the value should be incremented by
    * @return         the post-incremented value
   int increment(int delta) {

It’s worth noting that the comments are all formatted the same way, with the leading “/” indented to the same level as the code being remarked on.

The “@param” and “@return” tags are also included in the method comment. It shows the names of all the parameters and the method’s output. If you write “/**” after writing the method declaration, Eclipse will generate these for you automatically.

Including such comments is a brilliant idea, as you will be able to look back at your code and better comprehend it. Others will be able to grasp your code better as well. However, there are certain extra advantages to formatting them this way.

You can parse these comments with tools to provide documentation for your code (hence the name documentation comments). The Javadoc tools can read these comments, which will generate HTML-style documentation. Eclipse can read these comments as well. By typing an object name followed by the “.” operator, all methods provided by that object’s class will be listed.

When you hover your mouse over a method call, you’ll also see correctly formatted documentation. Further, when you add a new element to UML Lab, it will prompt you for feedback. If you make it a practice to type them immediately away, you won’t have to do more work to keep your code well-commented.

Creating Web Pages using Javadoc

The beauty of Javadocs is that the Java system understands how to read all Java elements’ comments and transform them into standardized, well-formatted, and easy-to-read web pages.

In Eclipse, all that is required is to accomplish the following:

  • Right-click the desired project in the Package Explorer.
  • Click Next after selecting Export…/Javadoc.
  • The “Javadoc command” may not be set the first time you generate Javadocs.
  • If it isn’t already set, click the configure button and navigate to the Java JDK installation folder, where the javadoc.exe file is located.
  • The complete source code will be picked by default.
  • Uncheck any packages you do not want documentation to be generated if desired.
  • For the produced visibility level, choose “Private.”
  • All available Javadocs will be generated as a result of this.
  • Choose the “standard doclet” Browser for your documentation’s destination folder.
  • It is usually a “doc” folder directly below the project’s root.
  • Subsequently, choose Next.
  • Click Finish after entering a relevant Document title.

For every one of the following, you must write documentation comments:

  • Interfaces and classes
  • All input parameters and return values
  • Methods
  • Fields

The Eclipse will utilize your comments to make your life easier, so you’ll experience the benefits right away.

All auto-generated fields and methods, such as those made by your GUI-creating tool, should also be commented. These include WindowBuilder or another code generator, such as UML Lab. The latter will allow Eclipse to show you what each variable does and considerably improve your ability to understand the code in the future. While the extra labor may look tedious, the advantages will surpass the effort. Commenting on things is always a good idea.

Internal “//” type comments are highly recommended for documenting what your code is attempting to accomplish. It will save you hours of troubleshooting time if you forget what a function is supposed to accomplish!

Remember to comment on any auto-generated method where you’ve written code in the method body, such as a button click listener’s actionPerformed function, to describe the behavior of your code!

Overridden Methods Documentation

While it may be tempting to skip documenting overriding methods (those marked with the annotation “@Override”), this is only justified if the implementing entity’s documentation would not contribute anything to the documentation supplied by the method’s abstract description. However, because every implementation of an abstract method differs somehow, this circumstance is relatively standard.

It’s critical to document such distinctions so that users of those methods know the variations between one implementation and the next.

Unfortunately, adding Javadocs to an overridden method replaces the documentation of the abstract method being overridden entirely. Because the abstract description is still relevant, it’s a good idea to include it in the implementation process’s updated documentation. Using the “{@inheritDoc}” tag, this is simple to accomplish:

	 * {@inheritDoc}
	 * This inserts the docs from the overridden method above.
	 * Implementation-specific docuementation can then be added here.
public void codeMethod() {


Tips for Creating Javadocs

Autogenerate @param and @return

Simply entering “/**Enter>” before a method or class in Eclipse will generate all required @param and @return attributes.

Warnings about “self-closing elements not allowed” are no longer displayed

The Javadoc compiler in the Java 8 JDK follows HTML 4.01 standards, which allow “void element” tags (tags with no enclosing content) like br and image to be written without the closing “/,” as in the more regularized HTML 5 standard:

  • HTML 4.01: <br>, <image …>
  • HTML 5: <br/>, <image …/>

Because of this adherence to the previous HTML standard, if an HTML 5 structured void element tag is encountered, Javadoc will throw a “self-closing element not allowed” warning by default. To prevent Javadoc from displaying this warning, use the following command line parameter:

  • -Xdoclint:all,-html

The HTML “lint” style checker is disabled due to this. Unfortunately, the Javadoc documentation is silent on what this setting disables other style checks.

When performing an Export/Javadoc operation in Eclipse, you can specify this option by typing the above option (including the initial “-” symbol) into the “Extra Javadoc options” box in the “Configure Javadoc arguments” dialog panel when it appears.

Set the compiler to notify you if you don’t have any Javadocs

Set the compiler to warn or issue errors on missing or malformed Javadocs in Eclipse’s Preferences/Java/Compiler/Javadoc. It is a great way to ensure that your code is correctly documented!

Sharing your Javadocs with others if you want to

Javadocs that is generated are simply HTML web pages. The drawback is that you’ll need a webserver to share them with others.

Fortunately, Rice provides a straightforward method for displaying web pages from your “U: drive”:

  • Hosting a personal website
  • Mounting your U: drive

All you have to do is copy your Javadocs to a folder under U:/Public/www, and they’ll be viewable in any browser. For more information on who to contact to determine the precise URL of your Javadocs, see the publications mentioned above.

Example: Program for illustrating the frequently used Comment tags in Java

* <h1>Find average of three numbers!</h1>
* The FindAvg program implements an application that
* simply calculates the average of three integers and Prints
* the output on the screen.
* @author Codeunderscored
* @version 1.0
* @since 2017-02-18
public class FindAvg
	* This method is used to find the average of three integers.
	* @param numA This is the first parameter to findAvg method
	* @param numB This is the second parameter to findAvg method
	* @param numC This is the second parameter to findAvg method
	* @return int This returns average of numA, numB and numC.
	public int findAvg(int numA, int numB, int numC)
		return (numA + numB + numC)/3;

	* This is the primary method that makes use of findAvg method.
	* @param args Unused.
	* @return Nothing.

	public static void main(String args[])
		FindAvg obj = new FindAvg();
		int avg = obj.findAvg(10, 20, 30);

		System.out.println("Average of 10, 20 and 30 is :" + avg);


You can use comments to explain and improve the readability of Java code. When evaluating alternative code, it is handly in preventing execution.

Comments in a program help make it more human-readable by putting the details of the code involved, and effective use of comments makes maintenance and bug-finding easier. When compiling a program, the compiler ignores comments.

The kind of comments in Java include:

  • Single–line comments.
  • Multi-line comments.
  • Documentation comments.

For illustrating the code functionality, a newbie programmer generally employs single-line comments. It’s one of the most straightforward comments to type. However, single-line comments might be tedious to write because we must offer ‘//’ at every line to describe a complete method in a code or a complex snippet. To get around this, you can utilize multi-line comments.

The documentation comments are commonly used while writing code for a project/software package because it aids in generating a documentation page for reference, which is used to learn about the methods available, their parameters, and so on.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *