Java Comments
What Are Comments in Java?
Java comments are text notes written inside the source code to explain what the code does. These notes are ignored by the compiler and do not affect the program’s output. Comments are mainly used for:
Explaining logic or functionality
Documenting code for future reference
Temporarily disabling code during testing
Improving code readability for other developers
Java comments are very similar to those in C and C++, making them familiar to programmers coming from those languages.
Types of Comments in Java
Java supports three types of comments:
Single-line comments
Multi-line comments
Documentation comments (JavaDoc)
1. Single-Line Comments
Single-line comments begin with //. Everything after // on that line is treated as a comment and ignored by the compiler.
Syntax
// This is a single-line comment
Example
public class Demo {
public static void main(String[] args) {
// Print a welcome message
System.out.println("Welcome to Java!");
}
}2. Multi-Line Comments
Multi-line comments begin with /* and end with */. They can span multiple lines and are useful for longer explanations or disabling blocks of code.
Syntax
/* This is a multi-line comment */
Example
public class Demo {
public static void main(String[] args) {
/* This program prints a message.
It demonstrates multi-line comments. */
System.out.println("Java is powerful!");
}
}3. Documentation Comments (JavaDoc)
Documentation comments begin with /** and end with */. They are used to generate HTML documentation using the javadoc tool. These comments are typically placed above class, method, or field declarations.
Example
/**
* This class performs basic math operations.
* @author Rizwan
* @version 1.0
*/
public class Calculator {
/**
* Adds two integers.
* @param a First number
* @param b Second number
* @return Sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
}To generate documentation, use:
javadoc Calculator.java
Benefits of Using Comments
Clarify complex logic
Improve code readability
Help with debugging and testing
Enable collaboration in teams
Generate professional documentation (JavaDoc)
Common Mistakes to Avoid
Practice Task
Create a Java class that includes a single-line comment, a multi-line comment, and a JavaDoc comment for a method.