Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

7.2 Documentation with JavaDoc

You can automatically create documentation for your applications using special Java comments in your source files, and you can then extract them with the javadoc tool. This has many advantages: Instead of having to go through a separate process of documentation (which people are less likely to do anyway), allowing the documentation to emerge directly from comments in the program itself means the docs are more likely to be up to date, complete, and standardized. Because the pages generated are HTML pages, they are immediately available for distribution in a common format. All of the HTML documentation for the Java API was generated using JavaDoc.

The javadoc tool comes with the standard JDK, and it is easy to use.

NOTE

This is the third tool we have looked at so far, javac for compilation and java for program execution being the others. You can view other tools available in the standard JDK by peeking into the <JAVA_HOME>/bin directory.

There are two requirements for creating this documentation: You must add the comments to your file, and then you must run the javadoc tool to extract the comments and create the HTML files from them.

The javadoc tool extracts comments for the following:

  • Packages

  • Public classes and interfaces

  • Public and protected methods

  • Public and protected fields

Private items are not included. It is a good idea to comment all of these items in your code. Write your comments immediately above the items in the code.

7.2.1 Creating JavaDoc Comments

You notate comments that you want to be picked up by javadoc like this:

/**
some comments
*/

Putting the extra * after the first comment line means that the compiler will rightly ignore your comment as a regular comment, but javadoc will know to pick it up. Note that any JavaDoc comments must be outside a method.

Generally, it is a good idea to include information about the creator, creation date of the file, and other information just as you would comment a ColdFusion custom tag:

/**
 * <p>Title: SomeClassFile</p>
 * <p>Description: This file prints <b>'Hello!'</b> to the command line</p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: WWWBooks</p>
 * @author E Hewitt
 * @version 1.0
 */
...class definition here...

Notice that in the comments there are two kinds of symbols used: HTML paragraph tags and the @ symbol. You can write any HTML in here, though the use of heading tags is generally discouraged because it can conflict with the JavaDoc formatting and distort the layout.

7.2.2 JavaDoc Tags

The @ symbol inside a JavaDoc comment denotes a tag. There are several tags you can use, and they display different kinds of information in the generated document. A description of each follows:

7.2.2.1 @author author

Documents the author of the class. Use one @author tag for each author. You might need to use the -author option during the javadoc execution for the @author field to be included.

7.2.2.2 @deprecated description

Indicates that the class, method, or variable is deprecated and should not be referenced in the future. The description text should indicate what to use instead of the deprecated item, for example:

 @deprecated Use <code>anotherMethod(String s)</code>

The description message may indicate other information about the nature of the deprecation; it can be used for classes, variables, and methods.

7.2.2.3 @docRoot path

Specifies the path to the root directory of this documentation.

7.2.2.4 @exception exceptionName and explanation

Identifies an exception that a method throws and describes in what circumstances the exception might occur. Can only be used for methods.

7.2.2.5 {@link name text}

Inserts a link inline to another item with related information. name indicates the name of a class or method to which the link will be added. The text is displayed.

7.2.2.6 @param name

Identifies a parameter for a method. Can only be used in documenting a method.

7.2.2.7 @return value

Identifies a method's return value. Can only be used in documenting a method.

7.2.2.8 @see link

Adds a hyperlink to more information, for example:

@see href
@see packageName.className#member text

The first way of writing this is to specify as href an absolute or relative URL. The second form specifies the name of a class in a package and, optionally, the name of a member. The text parameter is also optional.

7.2.2.9 @serial link

Adds a hyperlink in the "see also" section. More information on this tag appears below.

7.2.2.10 @serialData description

Comments the data written by the writeObject() and writeExternal() methods.

7.2.2.11 @serialField name type description

Comments an ObjectStreamField component.

7.2.2.12 @since versionNumber

Adds a since element. Its value should be a description of the release that first introduced this feature. For example, @since version 1.3.1. Can be used for documenting classes, variables, and methods.

7.2.2.13 @throws exceptionName and explanation

Has the same usage and meaning as the @exception tag.

7.2.2.14 @version description

Identifies the version of a class. Example:

@version version 1.0

You may need to explicitly specify the -version argument when using the javadoc utility.

7.2.3 Package Comments

You can create comments regarding your packages by adding a file named package.html to each package directory. All of the text you write between the <body> tags will be extracted when you run the javadoc command (we'll see how to do this in a moment).

7.2.4 Overview Comments

It is often useful to supply a general comment on all source files. To do this, create a file called overview.html in the parent directory for all application source files. As with the package.html file, anything between the <body> tags will be extracted. The comments are shown to the user when Overview is selected from the nav bar.

7.2.5 Doclets

Documentation using javadoc is a wonderful feature of the JDK. But all of the documentation conforms to the same look and feel as the docs that come with the JDK itself for describing classes in the Sun packages.

While you can specify your own stylesheet for use with javadoc, you may wish to include a more customized interface for your comments. If you have this kind of specialized requirement, doclets provide a way for you to create very customized documentation. See the online documentation on doclets at http://www.sun.com for more information.

7.2.6 Extracting Comments

In order to extract the JavaDoc comments you've written into your files, you use the javadoc command. Using the javadoc tool for extraction creates new HTML files in appropriate folders based on your comments. To do this, follow these steps:

  1. Navigate to the directory that contains the source files you wish to create documentation for. You must be in the parent directory for all of the application's source files (usually com). This directory also contains the overview.html file if you wrote one.

  2. If this is a single package, run the javadoc tool by issuing the command javadoc -d docsDirectory packageName. The docsDirectory here is the name of the directory you want to create the HTML files in.

  3. If you have multiple packages, run this command: javadoc -d docsDirectory packageName1 packageName2....

  4. If all of your files are in the default package, you can issue this command: javadoc -d docsDirectory *.java.

Note that you can use many different options when running the javadoc tool. To see what the options for this tool are, you can simply run javadoc. This will give you an error message that says you've not supplied the correct parameters, and it will therefore also show you all of the correct parameters, as shown in the next section.

7.2.7 JavaDoc Usage

Usage for the javadoc tool is shown below:

  usage: javadoc [options] [packagenames] [sourcefiles] [classnames] [@files]

Some of the notable arguments available are shown below:

-overview <file> Read overview documentation from HTML file

-public Show only public classes and members

-protected Show protected/public classes and members (default)

-package Show package/protected/public classes and members

-private Show all classes and members

-help Display command line options

-doclet <class> Generate output via alternate doclet

-docletpath <path> Specify where to find doclet class files

-sourcepath <pathlist> Specify where to find source files

-classpath <pathlist> Specify where to find user class files

-exclude <pkglist> Specify a list of packages to exclude

-subpackages <subpkglist> Specify subpackages to recursively load

-source <release> Provide source compatibility with specified release

-extdirs <dirlist> Override location of installed extensions

-verbose Output messages about what javadoc is doing

-locale <name> Locale to be used, e.g., en_US or en_US_WIN

-encoding <name> Source file encoding name

Some notable arguments include the ability to specify your own stylesheet for the documentation. If you don't specify one, your JavaDocs will look like the Sun JDK docs.

Let's write a simple class just to make some comments and see how they are generated into HTML documentation by JavaDoc.

7.2.8 Comments.java

/*
 * Comments.java
 *
 * Created on June 6, 2002, 9:09 AM
 */

package chp7;

/**
 * The <code>Comments</code> class is <i>very</i>
 * sophisticated. It's like a TS Eliot poem:
 * there are more comments than code!
 * @author eben hewitt
 * @version 1.0
 */
public class Comments {

  private String msg = "This is the Comments class.";

  /**
   * Public default constructor.
   * Creates a new Comments object.
   */
  public Comments() {
  }

  /**
  * @param args the command line arguments
  */
  public static void main (String args[]) {
    Comments myComments = new Comments();
    System.out.println(myComments.showMsg());
  }

  /**
   * This method gets the msg String and returns it.
   * @return The value of <code>msg</code>, which is a     
   * String message to the user
   */
  public String showMsg() {
    return msg;
  }

   /**
   * @deprecated This method is deprecated because it
   * breaks encapsulation.<br>
   * It has been replaced by showMsg().
   * @see Comments#showMsg() showMsg().
   *
   */
   public void printMsg() {
    System.out.println(msg);
  }
}

7.2.9 Generating the Comments.java JavaDoc

There are generally two ways to create the JavaDoc. You can do so at the command line, or you can use your IDE of choice. Here's how you would do it for Comments.java in Forte (Sun ONE Studio):

  1. Once you've written the comments and you're ready to create the JavaDoc, right click anywhere in your source code file. A context menu appears. Choose Tools > Generate JavaDoc.

  2. Forte generates the comments and asks if you would like to view them in a browser. If you have not specified a directory, Forte will automatically create the folders and files under a subdirectory of Forte, like this:

     C:\forte4j\bin\projects\javadoc\index.html.

Since this obviously isn't very workable, remember to use the @docRoot tag to specify a directory.

Here's what we type at the command line if you prefer this method:

  1. At the command prompt, navigate to the directory that contains the package you want to document.

  2. Type javadoc -d docsOutputDirectory nameOfPackage. To generate the docs for the Comments file in the chp7 package that we just wrote, I type this:

     C:\jdk1.4\JavaForCF>javadoc -d C:\MyJavaDocs chp7

The utility lets you know what it's doing, and after a moment, your directory will be created and you can view your documentation. Open the index.html page, and a link to the Comments class documentation will be presented. See Figure 7.1.

Figure 7.1Figure 7.1 Generated JavaDoc comments.


In ColdFusion it is very important to comment your work. While the javadoc utility makes it very easy to generate sophisticated and usable documentation, it also requires more effort: It forces you to comment everything that's public. It's a good practice to get into. We can't do it in the code examples in this book because of space considerations, but do comment your work.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020