Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 2 ■ JAVA SYNTAX


Listing 2-19. Bad style in a multi-line block comment

int counter /*
Please don't
do this */ = 0;

By convention (which I break to provide you with examples that you shouldn't emulate), multi-line
comments have the beginning of the comment (/*) on its own line, have the end of the comment (*/) on
its own line, and have each of the middle lines start with an asterisk, as shown in Listing 2-20.

Listing 2-20. Properly formatted multi-line block comment

/*
* Now is the time for all good coders to write meaningful comments,
* so that the rest of us can understand what the code is doing.
* And now this comment is properly formatted, too.
*/

This is easier to read, isn't it?

JAVADOC


Java includes a mechanism to generate documentation from within classes and interfaces. That
mechanism is called Javadoc, and it uses of a special kind of block comment (and here's a comment
meant for both humans and systems to read). A Javadoc comment starts with a slash and two asterisks
(/**) and ends with an asterisk and a slash (*/), much like a block comment but with an additional asterisk
in the starting syntax. The content of the comment then ends up in a document that the Javadoc tool
creates. By convention, any class meant for public consumption should have Javadoc comments on the
class and all methods that someone might use or extend (usually public and protected methods).

When the Javadoc tool runs, it examines all the classes and interfaces and creates a set of HTML pages (or
sometimes other output, depending on various settings) with headings and subheading corresponding to
the classes, interfaces, and methods in the program. Various markers help the Javadoc tool indicate
descriptions for arguments and return values, who wrote the Javadoc comment, and other special content.

When coding a program for yourself, you don't need to insert Javadoc comments. If you start coding for an
open-source project or for a company, you might be asked to add Javadoc comments to your code.

Listing 2-21 shows an example of a Javadoc comment and the method declaration it describes.
Free download pdf