Java Comments: Types, Usage, and Best Practices
Java Comments
This guide explains Java comments, why they matter, and how to use them correctly for clearer, more maintainable code.
In programming, comments are sections of source code that Java compilers ignore. They help developers understand code intent without affecting execution. For example:
// declare and initialize two variables
int a = 1;
int b = 3;
// print the output
System.out.println("This is output");
Here we used two comments: declare and initialize two variables and print the output.
Types of Comments in Java
Java supports two primary comment styles:
- Single‑line comment
- Multi‑line comment
Single‑Line Comment
A single‑line comment starts with // and extends to the end of the line. Example:
// "Hello, World!" program example
class Main {
public static void main(String[] args) {
// prints "Hello, World!"
System.out.println("Hello, World!");
}
}
Output:
Hello, World!
We used two single‑line comments: "Hello, World!" program example and prints "Hello, World!". The compiler ignores everything from // to the line’s end.
Multi‑Line Comment
When you need several lines, use /* … */. Example:
/* This is an example of a multi‑line comment.
* The program prints "Hello, World!" to the standard output.
*/
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output:
Hello, World!
The compiler skips everything between /* and */. This is also called a traditional comment.
Using Comments Effectively
Comments should not replace clear code. Write well‑structured, self‑describing code first, then add comments to explain the "why" behind decisions—complex algorithms, design choices, or non‑obvious logic.
While some advocate minimal comments, a concise explanation can greatly improve readability for future maintainers.
Note: Prefer comments that explain why a piece of code exists over how it works.
Java
- Mastering C# Comments: Types, Best Practices, and XML Documentation
- Master Java Operators: Types, Syntax, & Practical Examples
- Mastering Java if…else: Control Flow Explained
- Mastering Java's super Keyword: Advanced Usage & Practical Examples
- Mastering Java Interfaces: Concepts, Implementation, and Best Practices
- Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
- Java Annotations Explained: Types, Placement, and Practical Examples
- Mastering Comments in C: Writing Clear, Effective Notes
- Java Documentation Comments: Mastering Javadoc and Comment Types
- Mastering Comments in C++: Best Practices & Syntax