217

What's the difference between

/**
 * comment
 *
 *
 */

and

/*
 * 
 * comment
 *
 */

in Java? When should I use them?

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Dev
  • 13,492
  • 19
  • 81
  • 174

9 Answers9

256

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 37
    Another nice benefit of using Javadoc instead of simple block comments is that when you put a Javadoc comment before a Java element (f.ex. a method signature, a field declaration, a class etc.) this enables IDEs - at least Eclipse for sure - to show your comment (f.ex. in a tooltip) when you move the cursor - or hover with the mouse - on a reference to that Java element. – SantiBailors Apr 23 '15 at 11:10
  • Is it okay to use java doc comments for variables? – the_prole Jan 12 '18 at 21:40
  • @the_prole: You can, but I don't see much value in it unless it's part of a Constants sort of package. Even then, in-line comments have been more valuable in my experience. – Makoto Jan 12 '18 at 21:44
143

For the Java programming language, there is no difference between the two. Java has two types of comments: traditional comments (/* ... */) and end-of-line comments (// ...). See the Java Language Specification. So, for the Java programming language, both /* ... */ and /** ... */ are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).

However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular, /** ... */ comments are interpreted by the Javadoc tool, which is included in the Java platform and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between /** ... */ as documentation.

This is similar to tags like FIXME and TODO: if you include a comment like // TODO: fix this or // FIXME: do that, most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.

Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • 50
    +1 for making the important distinction that Javadoc syntax is not part of the language, which no other answer has currently captured. – Chris Hayes Apr 23 '15 at 08:23
  • 2
    This is why you can have a project that compiles just fine in Maven but as soon as you decide to attach JavaDocs it starts to complain because the `javadoc` tool can't interpret something. – Captain Man Feb 07 '17 at 16:23
  • @Hoopje I also always assumed there were 3 types of comments in Java (EOL, traditional and Javadoc)... But then I read the JLS which states as you say. Now, I'm far from understanding all that stuff going under the hood of the Java compiler, but after checking this [code](https://github.com/openjdk/jdk17/blob/4afbcaf55383ec2f5da53282a1547bac3d099e9d/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavaTokenizer.java#L921), it seems to me that even the Java compiler doesn't treat traditional and Javadoc comments all the same...To me it cleary distinguishes between 3 types of comments. – Patrick B. Apr 04 '22 at 21:23
  • @Hoopje Also, even in paragraph 3.7 of the JLS, it is stated : "// has no special meaning in comments that begin with /* or /**" which to me implicitly aknowledges the existence of two comment types besides end-of-line comments. So, am I missing something here? – Patrick B. Apr 04 '22 at 21:26
  • @PatrickB. About the JLS: The sentence you found is part of a comment which tries to explain the grammar productions in some more detail. Neither the bullet points at the beginning of the paragraph, nor the grammar productions treat JavaDoc comments differently. And there is no *need* to treat them differently: every JavaDoc comment is also a traditional comment, because "/*" is a prefix of "/**". And since comments are not part of the class file, for the Java compiler there is no difference. – Hoopje Apr 05 '22 at 18:03
  • @PatrickB. About the source code: I didn't write the source code, but I can imagine the reason the tokenizer collects comments is because it is not only used by the Java compiler, but also by other tools. For example, the JavaDoc tool itself surely re-uses a large part of the parser and code analyzer, because it not only uses the comments itself to generate the documentation, but also information such as method signatures, type hierarchies, etc. – Hoopje Apr 05 '22 at 18:09
  • @Hoopje In the JLS, the distinction with comments prefixed with /** is made starting at the 4th grammar production: > CommentTailStar: > /
    > * CommentTailStar > NotStarNotSlash CommentTail". Despite your answers, I still find some kind of ambiguousity on such a trivial matter. Even "official" [tutorials](https://docs.oracle.com/javase/tutorial/getStarted/application/index.html) (in which they say there are three "kinds" of comments) are misguiding ...
    – Patrick B. Apr 06 '22 at 20:41
  • @PatrickB. No, there they recognize the *end* of the comment. They need to remember if the last character is a star (CommentTailStar) or not (CommentTail) so that the comment can be closed if a slash follows the star. That's why they go back to CommentTail if the next character is NotStarNotSlash. – Hoopje Apr 08 '22 at 08:30
20

The first is Javadoc comments. They can be processed by the javadoc tool to generate the API documentation for your classes. The second is a normal block comment.

M A
  • 71,713
  • 13
  • 134
  • 174
15

Reading the section 3.7 of JLS well explain all you need to know about comments in Java.

There are two kinds of comments:

  • /* text */

A traditional comment: all the text from the ASCII characters /* to the ASCII characters */ is ignored (as in C and C++).

  • //text

An end-of-line comment: all the text from the ASCII characters // to the end of the line is ignored (as in C++).


About your question,

The first one

/**
 *
 */

is used to declare Javadoc Technology.

Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, interfaces, constructors, methods, and fields. You can use a Javadoc doclet to customize Javadoc output. A doclet is a program written with the Doclet API that specifies the content and format of the output to be generated by the tool. You can write a doclet to generate any kind of text file output, such as HTML, SGML, XML, RTF, and MIF. Oracle provides a standard doclet for generating HTML-format API documentation. Doclets can also be used to perform special tasks not related to producing API documentation.

For more information on Doclet refer to the API.

The second one, as explained clearly in JLS, will ignore all the text between /* and */ thus is used to create multiline comments.


Some other things you might want to know about comments in Java

  • Comments do not nest.
  • /* and */ have no special meaning in comments that begin with //.
  • // has no special meaning in comments that begin with /* or /**.
  • The lexical grammar implies that comments do not occur within character literals (§3.10.4) or string literals (§3.10.5).

Thus, the following text is a single complete comment:

/* this comment /* // /** ends here: */
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • Does the verb "to nest" has a special meaning from the JLS perspective than what we expect? To me, the following examples look like nested comments, at least visually (even if the compiler tokenization algorithm doesn't aknowledge the "inner" comments as "comments"): `/* outer comment //inner comment */`, `// outer comment //inner comment`, and `// outer comment /* inner comment */`. But certainly the following example doesn't show nested comments since the source code won't even compile : `/* outer comment /* inner comment */ */` – Patrick B. Apr 06 '22 at 20:54
8

I don't think the existing answers adequately addressed this part of the question:

When should I use them?

If you're writing an API that will be published or reused within your organization, you should write comprehensive Javadoc comments for every public class, method, and field, as well as protected methods and fields of non-final classes. Javadoc should cover everything that cannot be conveyed by the method signature, such as preconditions, postconditions, valid arguments, runtime exceptions, internal calls, etc.

If you're writing an internal API (one that's used by different parts of the same program), Javadoc is arguably less important. But for the benefit of maintenance programmers, you should still write Javadoc for any method or field where the correct usage or meaning is not immediately obvious.

The "killer feature" of Javadoc is that it's closely integrated with Eclipse and other IDEs. A developer only needs to hover their mouse pointer over an identifier to learn everything they need to know about it. Constantly referring to the documentation becomes second nature for experienced Java developers, which improves the quality of their own code. If your API isn't documented with Javadoc, experienced developers will not want to use it.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82
5

Comments in the following listing of Java Code are the greyed out characters:

/** 
 * The HelloWorldApp class implements an application that
 * simply displays "Hello World!" to the standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); //Display the string.
    }
}

The Java language supports three kinds of comments:

/* text */

The compiler ignores everything from /* to */.

/** documentation */

This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.

// text

The compiler ignores everything from // to the end of the line.

Now regarding when you should be using them:

Use // text when you want to comment a single line of code.

Use /* text */ when you want to comment multiple lines of code.

Use /** documentation */ when you would want to add some info about the program that can be used for automatic generation of program documentation.

shuttle87
  • 15,466
  • 11
  • 77
  • 106
Raj
  • 1,945
  • 20
  • 40
3

First one is for Javadoc you define on the top of classes, interfaces, methods etc. You can use Javadoc as the name suggest to document your code on what the class does or what method does etc and generate report on it.

Second one is code block comment. Say for example you have some code block which you do not want compiler to interpret then you use code block comment.

another one is // this you use on statement level to specify what the proceeding lines of codes are supposed to do.

There are some other also like //TODO, this will mark that you want to do something later on that place

//FIXME you can use when you have some temporary solution but you want to visit later and make it better.

Hope this helps

sunny
  • 303
  • 2
  • 7
3
  • Single comment e.g.: //comment
  • Multi Line comment e.g: /* comment */
  • javadoc comment e.g: /** comment */
Ramlal S
  • 1,573
  • 1
  • 14
  • 34
-1

Java supports two types of comments:

  • /* multiline comment */ : The compiler ignores everything from /* to */. The comment can span over multiple lines.

  • // single line : The compiler ignores everything from // to the end of the line.

Some tool such as javadoc use a special multiline comment for their purpose. For example /** doc comment */ is a documentation comment used by javadoc when preparing the automatically generated documentation, but for Java it's a simple multiline comment.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
Ranjeet
  • 636
  • 6
  • 12
  • 12
    The Java language only supports two types of comments. A comment in the form of `/** .. */` is just a regular multiline comment, and the first character inside it happens to be an asterisk. – Chris Hayes Apr 23 '15 at 08:22