Java Comments
A comment in Java is text in your source code that the compiler ignores. Comments let you leave notes for yourself and other programmers explaining what the code does, without changing how the program runs.
Why use comments?
As programs grow, it becomes harder to remember why you wrote something a certain way. Comments help you and others understand the code later. They are also useful for temporarily disabling a line of code while testing.
Single-line comments
A single-line comment starts with two forward slashes //. Everything after // on that line is ignored by the compiler.
// This line prints a greeting
System.out.println("Hello, Java!");
Multi-line comments
A multi-line comment starts with /* and ends with */. Everything between those symbols, even across several lines, is ignored.
/* This is a comment
that spans
multiple lines */
Example
Here is a complete program that uses both types of comments:
public class Main {
public static void main(String[] args) {
// This is a single-line comment
System.out.println("Hello, Java!"); // prints a greeting
/* This is a
multi-line comment */
System.out.println("Comments do not affect the output.");
}
}
Output:
Hello, Java!
Comments do not affect the output.
How it works
When the Java compiler reads your source file, it strips out everything marked as a comment before compiling. This means comments have no effect on the program’s behavior or its output — they exist purely for humans reading the code.
Placement
Comments can appear on their own line, at the end of a line of code, or wrapped around several lines of code. A multi-line comment cannot be nested inside another multi-line comment.
Good practices
- Explain why the code does something, not just what it does — the code itself usually shows the what.
- Keep comments short and up to date; a comment that no longer matches the code is worse than no comment.
- Avoid over-commenting obvious lines, such as
// declare a variableabove a variable declaration.
Comments are a small but essential tool for writing readable Java code. In the next lesson, you’ll start working with Java variables.
