How to Comment in Java: Syntax and Examples
In Java, you can add comments using
// for single-line comments, /* ... */ for multi-line comments, and /** ... */ for documentation comments. Comments are ignored by the computer and help explain your code to others or yourself.Syntax
Java supports three types of comments:
- Single-line comment: Starts with
//and continues to the end of the line. - Multi-line comment: Starts with
/*and ends with*/, can span multiple lines. - Documentation comment: Starts with
/**and ends with*/, used to generate documentation.
java
// This is a single-line comment /* This is a multi-line comment It can span several lines */ /** * This is a documentation comment * It is used by tools like Javadoc */
Example
This example shows all three comment types in a simple Java program that prints a message.
java
public class CommentExample { public static void main(String[] args) { // Print a greeting message System.out.println("Hello, world!"); /* This is a multi-line comment. It explains that the program ends here. */ } /** * This method is not used but shows a documentation comment. * @return A greeting string */ public static String greet() { return "Hello!"; } }
Output
Hello, world!
Common Pitfalls
Common mistakes when commenting in Java include:
- Forgetting to close multi-line comments, which causes errors.
- Using
//for multi-line comments instead of/* ... */. - Placing comments inside string literals, which does not create a comment.
java
// Wrong: multi-line comment not closed /* This comment starts but never ends */ // Right: properly closed multi-line comment /* This comment starts and ends properly */
Quick Reference
| Comment Type | Syntax | Use Case |
|---|---|---|
| Single-line | // comment text | Short notes or explanations on one line |
| Multi-line | /* comment text */ | Longer explanations spanning multiple lines |
| Documentation | /** comment text */ | Generate API docs with Javadoc tool |
Key Takeaways
Use // for single-line comments to explain brief points.
Use /* ... */ for multi-line comments to explain longer ideas.
Use /** ... */ for documentation comments to create API docs.
Always close multi-line comments properly to avoid errors.
Comments do not affect program execution but improve code readability.