/** and /* in Java Comments

Dev picture Dev · Apr 23, 2015 · Viewed 257.9k times · Source

What's the difference between

/**
 * comment
 *
 *
 */

and

/*
 * 
 * comment
 *
 */

in Java? When should I use them?

Answer

Makoto picture Makoto · Apr 23, 2015

The first form is called Javadoc. You use this when you're writing formal APIs for your code, which are generated by the javadoc tool. For an example, the Java 7 API page uses Javadoc and was generated by that tool.

Some common elements you'd see in Javadoc include:

  • @param: this is used to indicate what parameters are being passed to a method, and what value they're expected to have

  • @return: this is used to indicate what result the method is going to give back

  • @throws: this is used to indicate that a method throws an exception or error in case of certain input

  • @since: this is used to indicate the earliest Java version this class or function was available in

As an example, here's Javadoc for the compare method of Integer:

/**
 * Compares two {@code int} values numerically.
 * The value returned is identical to what would be returned by:
 * <pre>
 *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
 * </pre>
 *
 * @param  x the first {@code int} to compare
 * @param  y the second {@code int} to compare
 * @return the value {@code 0} if {@code x == y};
 *         a value less than {@code 0} if {@code x < y}; and
 *         a value greater than {@code 0} if {@code x > y}
 * @since 1.7
 */
public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

The second form is a block (multi-line) comment. You use this if you want to have multiple lines in a comment.

I will say that you'd only want to use the latter form sparingly; that is, you don't want to overburden your code with block comments that don't describe what behaviors the method/complex function is supposed to have.

Since Javadoc is the more descriptive of the two, and you can generate actual documentation as a result of using it, using Javadoc would be more preferable to simple block comments.