Comments in Java: Single-Line and Multi-Line
You'll learn how to add notes inside your Java code that the compiler ignores, making your programs easier to understand.
What Are Comments?
Comments are lines of text you write inside your Java source file that are not executed. They exist purely for humans—to explain what the code does, why you made certain decisions, or to temporarily disable code. The javac compiler skips over them entirely.
Think of comments like sticky notes you place on a recipe. They don't change how you cook the dish, but they help you (or someone else) understand your thinking.
Single-Line Comments
Use // to create a comment that runs until the end of that line:
public class HelloWorld {
public static void main(String[] args) {
// This prints a greeting to the console
System.out.println("Hello, World!");
}
}
Everything after // on that line is ignored by the compiler.
Multi-Line Comments
Use /* to start and */ to end a comment that spans multiple lines:
public class HelloWorld {
public static void main(String[] args) {
/*
This is a longer explanation.
It can span several lines.
Useful for detailed notes.
*/
System.out.println("Hello, World!");
}
}
This style is convenient when you need to write paragraph-length explanations or temporarily "comment out" several lines of code at once.
When to Use Comments
- Explain why you're doing something that might not be obvious
- Document the purpose of your
mainmethod or program - Leave reminders for yourself or teammates
Key Takeaway: Use // for single-line comments and /* */ for multi-line comments to document your Java code without affecting how it compiles or runs.