TOPIC 1.8 · STUDY
Documentation with Comments
Java comments document code for human readers and are skipped by the compiler. Use // for the rest of a line, /* */ for a block, and /** */ for Javadoc. Commented text does not run, so a commented assignment leaves the variable unchanged.
1.8.A
Documentation with comments
A comment is text the compiler ignores. It explains what the code is meant to do, or it can temporarily hide statements while you test. Commented code is not executed. Three forms appear in this course: a line comment that runs to the end of the line, a block comment wrapped in /* and */, and a Javadoc documentation comment wrapped in /** and */.
int trays = 2; // trays = 7;
System.out.print(trays);
The line comment hides the assignment trays = 7. Only trays = 2 runs, so the program prints 2. The variable keeps its earlier value because the second assignment never executes.
| Form | How it looks | What it covers |
|---|---|---|
| Line comment | // ... | From // to the end of that line |
| Block comment | /* ... */ | Any text between /* and */, including several statements |
| Javadoc comment | /** ... */ | Documentation for readers, often placed above a method |
A block comment can hide several statements at once. Everything between /* and */ is skipped, so updates inside that region never change variables. A Javadoc comment describes a method for other programmers reading the source or generated API docs. It is documentation for people. It is not a substitute for compiling and running the code to see what actually happens.
The left statement runs. The right assignment is only comment text, so trays stays 2.
Key points
- Commented code is not executed.
- // comments from that mark to the end of the line.
- /* */ can hide one statement or several statements.
- /** */ Javadoc describes a method for readers; it does not run the method.
- A line comment can hide an assignment so the variable keeps its earlier value.
A comment does not change a value unless you remove the comment and the code actually runs. Text after // or inside /* */ or /** */ is ignored until it becomes live source again.