What Are Comments in Java?
Comments are notes or explanations placed within your code to make it more readable or to describe its functionality.
The compiler ignores comments — they do not affect your code’s execution.
Types of Comments in Java
1️⃣ Single-Line Comments (//
)
- Comments everything after
//
until the end of the line.
// This is a single-line comment
public class CommentsExample {
public static void main(String[] args) {
// Prints a message to console
System.out.println("Hello, Java!");
}
}
2️⃣ Multi-Line Comments (/* */
)
- Comments everything between
/*
and */
— can span multiple lines.
/*
This is a multi-line comment.
It can be used to describe the code in more depth.
*/
public class CommentsExample {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
3️⃣ Javadoc Comments (/** */
)
- Mainly used to describe classes, methods, or fields.
- Allows you to generate API documentation.
/**
* This class prints a greeting message.
*/
public class CommentsExample {
/**
* Prints "Hello, Java!" to the console.
*/
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Summary
- Comments help make your code more readable and maintainable.
- Comments do not affect your code’s functionality.
- Always write clear and helpful comments when coding.