Comments in Java

In Java, comments are statements ignored by the compiler, used to make the code more readable and to provide documentation.


  • Comments improve code readability and help developers understand logic easily.

  • Java supports three types of comments: Single-line, Multi-line, and Documentation (Javadoc) comments.

  • Documentation comments can be used to generate API docs using Javadoc tool.

Single-line Comment

Used for small explanations. Starts with //.

// This is a single-line comment
public class Demo {
    public static void main(String[] args) {
        System.out.println("Hello World"); // Prints Hello World
    }
}
    

Multi-line Comment

Used when you need to write explanations spanning multiple lines. Enclosed in /* ... */.

/*
 This is a multi-line comment
 It can span across multiple lines
*/
public class MultiLineDemo {
    public static void main(String[] args) {
        System.out.println("Example with multi-line comment");
    }
}
    

Documentation Comment

Special type of comment used to generate documentation. Enclosed in /** ... */ and processed by Javadoc tool.

/**
 * This class demonstrates documentation comment.
 * @author ProwessApps
 * @version 1.0
 */
public class DocDemo {
    /**
     * This method adds two numbers.
     * @param a first number
     * @param b second number
     * @return sum of a and b
     */
    public int add(int a, int b) {
        return a + b;
    }
}
    
Notes
  • Single-line comments are best for short explanations.
  • Multi-line comments are useful for detailed descriptions.
  • Documentation comments can be extracted into HTML docs using javadoc.
  • Comments are ignored by the compiler; they do not affect program execution.

Next: Java Operators



πŸš€ Quick Knowledge Check

Topic: Comments | Language: Java

Q1. Which type of comment is best for multiple lines in Java?
Q2. Which tool processes Java documentation comments?
/** Example comment */
Q3. What happens if comments are placed inside code in Java?
System.out.println(10 /* comment */ + 20);
Q4. Which symbol is used for single-line comments in Java?
Q5. Which of the following is a valid documentation comment in Java?