Overview
A comment is a note in the source code that explains what the code does.
The Java compiler ignores comments completely, so they never change how the program runs.
This program shows a single-line comment, which starts with //.
Everything after // up to the end of that line is a comment. The code before // on the same line still runs normally.
Step-by-Step Explanation
1
Class Declaration
The container for the program.
public class SingleLineComment {
...
}
The class is named SingleLineComment, so the file must be saved as SingleLineComment.java.
2
The main() Method
Where the program starts.
public static void main(String[] args)
The JVM starts running the program from this method.
3
Variable with a Single-Line Comment
Code and comment on the same line.
int i = 10; // This is a single-line comment: i is a variable
int i = 10; creates an integer variable named i and stores 10 in it.
The text after // is the comment. The compiler skips it.
4
Print the Value
Shows the result on the screen.
System.out.println(i);
This prints the value stored in i, which is 10. There are no quotes around i, so Java prints the variable's value, not the letter "i".
Types of Comments in Java
| Type |
Syntax |
Use |
| Single-line |
// comment |
Short notes on one line |
| Multi-line |
/* comment */ |
Longer notes across several lines |
| Documentation |
/** comment */ |
Used by the javadoc tool to create documentation |
Where You Can Place a Single-Line Comment
// Comment on its own line
int i = 10;
int j = 20; // Comment at the end of a line of code
Output
10
Common Mistakes
Putting code after //
// int i = 10; turns the whole statement into a comment, so i is never declared and System.out.println(i) gives a compile error.
Using a single slash
/ comment isn't a comment. Java reads it as a division operator and gives an error.
Writing comments that state the obvious
A comment like // set i to 10 adds nothing. Explain why the code does something, not just what it does.
Good practice
Use // to temporarily switch off a line of code while testing, then remove the // to switch it back on.
Key Takeaway
A single-line comment starts with // and runs to the end of the line.
The compiler ignores it, so it helps people understand the code without changing the output.