Java Comments

In Java, comments are lines in the code that the compiler ignores during program execution. They are used to explain the code, improve readability, or temporarily disable parts of the program. Proper use of comments makes your code easier to understand, especially for others or when revisiting your own code after a while.

Types of Comments in Java

Java supports three types of comments:

1. Single-Line Comments

  1. Starts with //

2. Used for short, explanatory notes or to temporarily disable a single line of code.

Syntax:


// This is a single-line comment
System.out.println("This line will execute.");
// System.out.println("This line is commented out and won't execute.");

2. Multi-Line Comments

  1. Starts with /* and ends with */.
  2. Used for longer explanations or to temporarily disable multiple lines of code.

Syntax:


/*
This is a multi-line comment.
It can span across multiple lines.
*/
System.out.println("Multi-line comments are useful for large blocks of text.");

3. Documentation Comments (Javadoc)

  1. Starts with /** and ends with */.
  2. Used to create API documentation for classes, methods, and other elements.
  3. Extracted using the javadoc tool to generate HTML documentation.

Syntax:


/**
 * This is a documentation comment.
 * It describes the purpose of the class or method.
 */
public class HelloWorld {
    /**
     * The main method is the entry point of the program.
     * @param args Command-line arguments
     */
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}