CodeGym /Java Blog /Core Java /Java Comments
Author
Andrey Gorkovenko
Frontend Engineer at NFON AG

Java Comments

Published in the Core Java group
Comments are the part of a program that’s not executed. The compiler simply ignores comments because they aren’t intended for it. They’re written in “human” language and are intended to explain the program, part of the program, a single line or method for developers or people involved in the development. Most often, comments are written in English, it’s kind of a tradition. In this article, we are going to talk about comments in Java and how to use them correctly to make life easier for you and your teammates.

Java Comments: why they are important

They say programmers are extremely lazy when it comes to commenting on their own code. However, this is a very important skill, so don’t underestimate it, even if you are just starting to learn Java. Well-commented code is much more valuable than code without comments because such a program is much easier to maintain. Since large projects are most often written in Java, competent commenting also speeds up development, since it is easier for a programmer to deal with other people's code. Comments are needed in order to:
  • Understand the code. Yours or someone else's. If it seems to you that you don’t need to decipher your own code because you wrote it, try opening a relatively complex program that you wrote a month ago or even earlier and quickly understand what, where and why you had in mind. Comments can be used to explain the logic of a program or block of a program, as well as leave recommendations for those who will work with your code later. This type of comment can be called explanatory.

  • Containing information about the purpose of objects, input and output parameters (if any), data about the developer, and other important things related to the code fragment. Such comments are located in the headers of modules, libraries, procedures, and functions. They can be called documentation comments.

  • Control bugs and improve code. Questionable code or code that needs improvement can always be commented out and revisited later. If it occurs to you that a certain problem can be solved in a different way, but now you don’t have time for it, write this idea in the comment. Otherwise, most likely, under the pressure of new code, you will forget about it.

Types of comments in Java

Despite the fact that you can write anything and everything in the comments, there are certain types of comments in Java and rules for using them. In Java comments cold be:
  • Single line comments
  • Multi line comments
  • Documentation comments

Single line comments

The most common Java comments are single line comments. To indicate such a comment, it is enough to put a double slash before the text //. Single line comments are flagged only at the beginning of the comment. Comment continues to the end of the line. Syntax:

//here is a single line comment.
Let’s take an example of this type of Java comments:

public class CommentsDemo1 {
   public static void main(String[] args) {
       System.out.println("This text is visible for Java compiler");
       //this text is single line comment 
//This one is also single line comment
//they both (and me) are invisible for compiler
   }
}
The output is:
This text is visible for Java compiler
Usually a single-line comment is located above or below the commented place in the program, occasionally on the same line. It is important that it is visually clear what the comment refers to.

Multi-line Comments

Sometimes there’s not enough one line to write a Java comment. For example, you need to describe how a method works or a complex formula that you are implementing. In this case, you can write several single-line comments, but it would be more rational to write so-called multi-line comments. They’re marked on both sides with the symbols /* */. Syntax of multi-line comments:

/*This comment 
is
Multi line comment 
we can describe here 
what we need */
Let’s have an example of multi-line comments in code

public class RleTest {

   /*
   Run Length Encoding (RLE),  a data compression algorithm
   that replaces repeated characters (series)
   with one character and the number of its repetitions.
  
   this method is to decode a String using run-length encoding

    */
   private static String decodeRle(String encoded) {
       if (encoded.isBlank()) return "";
       StringBuilder result = new StringBuilder();
       int count = 0;
       char baseChar = encoded.charAt(0);
       for (int i = 1; i <= encoded.length(); i++) {
           char c = i == encoded.length() ? '$' : encoded.charAt(i);
           if (Character.isDigit(c)) {
               count = count * 10 + Character.digit(c, 10);
           } else {
               do {
                   result.append(baseChar);
                   count--;
               } while (count > 0);
               count = 0;
               baseChar = c;
           }
       }
       return result.toString();
   }
   public static void main(String[] args) {
       System.out.println(decodeRle("C3ecddf8"));
   }
}

Java Documentation Comments

This is a special type of Java comments that are used to generate a documentation page. Usually developers write documentation comments using Javadoc, a documentation generator for generating API documentation in HTML format from Java source code. The format of documents used by Javadoc is the industry standard for documenting Java classes and the most popular IDEs such IntelliJ IDEA and Eclipse, automatically generate Javadoc HTML. Java documentation comments have the syntax below:

/**
Some important Javadoc comments here 
You don’t know it yet, but Javadoc rulez 

@author  Java Developer
*/
Java Comments - 1Here is an example: it's a fragment of Java Short class. By the way, you can look at any Java class code from your IDE (for example in IntelliJ IDEA from Windows just press ctrl+LBM or ctrl + b (in Windows) on any class or method’s name).

package java.lang;

import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.misc.VM;

/**
* The {@code Short} class wraps a value of primitive type {@code
* short} in an object.  An object of type {@code Short} contains a
* single field whose type is {@code short}.
*
* <p>In addition, this class provides several methods for converting
* a {@code short} to a {@code String} and a {@code String} to a
* {@code short}, as well as other constants and methods useful when
* dealing with a {@code short}.
*
* @author  Nakul Saraiya
* @author  Joseph D. Darcy
* @see     java.lang.Number
* @since   1.1
*/
public final class Short extends Number implements Comparable<Short> {

   /**
    * A constant holding the minimum value a {@code short} can
    * have, -2<sup>15</sup>.
    */
   public static final short   MIN_VALUE = -32768;

   /**
    * A constant holding the maximum value a {@code short} can
    * have, 2<sup>15</sup>-1.
    */
   public static final short   MAX_VALUE = 32767;

   /**
    * The {@code Class} instance representing the primitive type
    * {@code short}.
    */
   @SuppressWarnings("unchecked")
Here is Java code of the well-known and loved by all newbies println() method with such comment:

/**
* Prints a String and then terminate the line.  This method behaves as
* though it invokes {@link #print(String)} and then
* {@link #println()}.
*
* @param x  The {@code String} to be printed.
*/
public void println(String x) {
   if (getClass() == PrintStream.class) {
       writeln(String.valueOf(x));
   } else {
       synchronized (this) {
           print(x);
           newLine();
       }
   }
}
Javadoc has some special Javadoc tags marked with @ you can see in the code above. The example of such a Javadoc tag is @author that adds a name of the class author. Another Javadoc tag is @since it adds a comment indicating that this class is used since the specified version of Java. Writing good Javadoc documents requires knowledge and experience (and patience!). You can find more information on Javadoc in the official documentation How to Write Doc Comments for the Javadoc Tool.

P. S. some funny comments examples from real life


/**
*Dear Maintainer
*
*Once you are done trying to 'optimize' this routine,
*and you have realized what a terrible mistake that was,
*please increment the following counter as a warning
*to the next guy.
*
*total_hours_wasted_here = 73
*/

Exception up = new Exception("Something is really wrong.");
throw up;  //ha ha

// When I wrote this, only God and I understood what I was doing
// Now, God only knows

// sometimes I believe compiler ignores all my comments

/**
Always returns true.
*/
public boolean isAvailable() {
return false;
}
To reinforce what you learned, we suggest you watch a video lesson from our Java Course
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION