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
- 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
- Starts with
/*and ends with*/. - 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)
- Starts with
/**and ends with*/. - Used to create API documentation for classes, methods, and other elements.
- 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!");
}
}
Java Comments – Questions and Answers
Q 1: What are comments in Java?
Ans: Comments are used to explain code and improve readability.
Q 2: How many types of comments exist in Java?
Ans: Single-line, multi-line, and documentation comments.
Q 3: Which symbol is used for multi-line comments?
Ans: /* */
Q 4: What is JavaDoc?
Ans: A tool used to generate documentation from comments.
Q 5: Do comments affect program execution?
Ans: No, comments are ignored by the compiler.
Java Comments – Objective Questions (MCQs)
Q1. Which of the following is the correct syntax for a single-line comment in Java?
Q2. What is the purpose of using comments in Java code?
Q3. Which of the following is a multi-line comment in Java?
Q4. Which of the following is the correct syntax for a documentation comment in Java?
Q5. What happens if a comment is placed inside a block of code in Java?