Comments in Java
Every great codebase tells a story — not just through what it does, but through how clearly it’s explained.
Comments don’t affect how a program runs. Instead, they help other people (and your future self) understand, maintain, and debug the code more easily.
You can use comments to:
- Clarify complex logic
- Mark sections for future improvement
- Disable parts of the code temporarily
- Generate documentation (JavaDoc)
Types of Comments in Java
Java supports three main types of comments:
- Single-line Comments
- Multi-line Comments
- Documentation Comments
1. Single-line Comments
These are used for short explanations or notes.
// This is a single-line comment
System.out.println("Hello, World!"); // Print statement
Here is a simple example, where we use single line comments when doing addition of two numbers.
public class AdditionExample {
public static void main(String[] args) {
// Declare two integer variables and assign values
int num1 = 10;
int num2 = 20;
// Add the two numbers and store the result in sum
int sum = num1 + num2;
// Print the result to the console
System.out.println("The sum is: " + sum);
}
}
Hello, World!
Explanation: The lines starting with // are ignored by the compiler. Only the System.out.println() line executes and prints the output.
2. Multi-line Comments
Multi-line Comments are used when you want to explain something in more than one line. These can also be used to temporarily disable blocks of code during testing or debugging.
/* This is a multi-line comment.
It can span several lines.
Useful for detailed notes or explanations. */
System.out.println("Multi-line comment demo");
Multi-line comment demo
Note: Everything between /* and */ is ignored by the compiler.
3. Documentation Comments (JavaDoc)
Specially formatted comments used to generate official documentation. These comments are placed just before class, method, or field declarations.
/**
* This class demonstrates JavaDoc comments.
* @author Mallikarjuna
* @version 1.0
*/
public class Example {
/**
* This method prints a greeting.
* @param name The name to greet
*/
public void greet(String name) {
System.out.println("Hello, " + name);
}
}
Usage Tip: Use the javadoc tool to generate HTML documentation from JavaDoc comments:
javadoc Example.java

About the authorMallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗