Comments in Java
Line //, block /* */ and Javadoc /** */ comments.
Notes for humans
Comments are text the compiler skips. They're for people reading the code. A // comment runs from the // to the end of that line.
int lives = 3; // starting lives
// this whole line is ignoredBlock and Javadoc comments
/* ... */ is a block comment that can span many lines. /** ... */ is a Javadoc comment, placed above classes and methods. The javadoc tool reads these and generates HTML API documentation.
/** Adds two numbers. */
int add(int a, int b) {
/* simple sum,
* no overflow check */
return a + b;
}Your turn
What does this print?
System.out.println("1");
// System.out.println("2");
/* System.out.println("3"); */
System.out.println("4"); // "5"1 41 2 3 41 4 5
Show the answer
Only the 1 and 4 lines are real code. 2 and 3 sit inside comments, and "5" is part of a trailing // comment. Output: 1 and 4.
Block comments don't nest
A block comment ends at the first */ Java sees, no matter how many /* came before. A second /* inside a comment is just ordinary comment text.
The nesting trap
You wrap code in /* */ to disable it, but it already contains a block comment. The comment ends at the first */ (after set x), so y = 2; becomes real code, and the final */ is a syntax error.
/* disable this part:
x = 1; /* set x */
y = 2;
*/A safer way
How can you comment out lines that already contain /* */ comments?
Think about it, then reveal the answer
Put // in front of each line. Line comments can't be cut short by */. Most editors do this with one shortcut (Cmd+/ or Ctrl+/).
In real projects
Java's official API docs are generated by javadoc from /** */ comments in the JDK's own source. Good teams comment why code does something; the code itself already says what it does.
Key takeaways
- // … ends at the line break
- /* … */ can span lines but does not nest
- /** … */ is Javadoc, used to generate API docs
Java translates \u Unicode escapes before finding comments. So // \u000a System.out.println("hi"); really prints hi: \u000a is a line break that ends the comment early!
Practice questions
Which JDK tool turns /** */ comments into HTML documentation?
- javac
- jshell
- javadoc
- jar
Check your answer
javadoc. javadoc reads the Javadoc comments on classes, methods and fields and builds browsable HTML API docs.
What does this print?
// System.out.println("A");
System.out.println("B"); // "C"
/* System.out.println("D"); */- A B D
- B C
- B
- B "C"
Check your answer
B. Only the middle println is real code. A and D sit inside comments, and "C" is part of the trailing // comment.