Javadoc Comments

Documentation Comments

A comment starting with /** is a Javadoc comment. The javadoc tool turns them into HTML documentation (the official Java API docs are made this way). IDEs show them when you hover over a method.

/**
 * Calculates the final price after a discount.
 *
 * @param price    original price in rupees
 * @param discount discount percentage, for example 10 for 10%
 * @return the price after the discount
 */
public static double applyDiscount(double price, double discount) {
    return price - price * discount / 100;
}

Common Javadoc Tags

TagMeaning
@param namedescribes a parameter
@returndescribes the return value
@throws Typedescribes an exception the method may throw
@author, @since, @seeauthor, version added, related item
@deprecatedmarks an old API that should not be used

Run javadoc

Generate HTML docs for your code:

javadoc -d docs Main.java

Example output

Generating docs\Main.html...
Generating docs\index.html...

Good Comment Habits

  • Explain why, not what: i++; // increment i is useless; // retry once because the payment API sometimes times out is useful.
  • Keep comments up to date. A wrong comment is worse than no comment.
  • Prefer clear variable and method names over long comments.
  • Write Javadoc for public methods that other developers will call.