Comments and Javadoc
Write the three comment forms, and document an API the way the tooling expects.
Open this lesson in the learning hubKey points
- Three forms:
//to the end of the line,/* ... */across lines, and/** ... */for Javadoc. - javac strips every comment. None of them reach the
.classfile or cost anything at runtime. - A Javadoc block sits above the member it describes and uses
@param,@returnand@throws. - Document why, not what. A comment that restates the code goes stale the moment the code changes.
- If a comment is needed to explain what a line does, a better name or a small extracted method usually removes the need.
- Never comment out dead code — delete it. Version control already remembers it.
Example
/**
* Demonstrates the three comment forms Java understands.
*
* <p>This header is Javadoc. The javadoc tool turns it into browsable HTML,
* and an IDE shows it when you hover the class.
*/
public class Main {
/**
* Adds a tip to a bill.
*
* @param bill the amount before the tip
* @param percent the tip percentage, 0 to 100
* @return the total including the tip
* @throws IllegalArgumentException if percent is negative
*/
static double withTip(double bill, double percent) {
if (percent < 0) throw new IllegalArgumentException("percent must not be negative");
// WHY, not WHAT: the tip is charged on the pre-tax bill by house policy
return bill + bill * percent / 100;
}
public static void main(String[] args) {
/* A block comment
can span several lines. */
System.out.println("bill 40 with a 10% tip = " + withTip(40, 10));
// A line comment runs to the end of the line.
System.out.println("javac strips every comment - none of them reach the .class file");
System.out.println("Javadoc blocks describe the API: @param, @return, @throws");
System.out.println("A comment that repeats the code is noise; delete it and rename instead");
}
}
Javadoc states the contract; a line comment states the reason.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.