Objective Viewpoint column

Using the Java Document Generator

by Kevin Henry

Introduction

Any software project, more serious than "Hello World," needs documentation. Often, documentation takes the form of early requirements specifications, user's guides, or line by line comments within the actual source code. Good documentation allow much easier use, maintenance, and reuse of finished software products. Documentation can also serve as a guide for software engineers as they create software.

Java programmers have become familiar with the online Java API documentation, available from Sun and mirrored elsewhere [8]. This professional looking style of code documentation is created semi-automatically from commented source code by the javadoc tool, which comes standard with the Java Software Development Kit (SDK). Java programmers already use javac and java to create and execute programs, now it's time to add the API Document Generator to your toolbox.

Why use Javadoc?

Javadoc creates code documentation that is easy to read and understand. The HTML pages it generates are easy to post on Web sites and can be easily distributed to a software team. Many programmers often neglect documentation, but Javadoc provides an opportunity to create very professional looking API specifications that require little overhead to create. In addition, documentation is produced directly from source code files. Consequently, no separate documentation files are necessary.

Javadoc facilitates good software engineering by allowing programmers to work concurrently on different parts of a system. The object relationships specified by class interfaces can all be defined in the Javadoc generated HTML API documentation. Good API documentation allows programmers to access documentation for every component within a software system. Even if these components are still being coded, the engineer can use knowledge of their interfaces to write tighter, more integrated code.

Maintenance is not a problem for an API made with Javadoc. Interfaces and method signatures can be kept constant as code is modified. The HTML documentation may be optionally updated to reflect or at least mention changes in the implementation; but that is not necessary.

How Javadoc Works

Javadoc creates HTML pages of documentation for programs or custom API, as defined in Java source code files. By calling the tool on the command line, you instruct Javadoc to parse certain source code files or packages and create Web pages describing the public and protected interfaces, constructors, methods, and fields of your public, protected, and inner classes.

Programmers write Javadoc comment blocks within the source code of a program. Javadoc parses the raw source code files looking for Javadoc comment blocks and constructs indexed documentation from them. Javadoc creates a page for each class, with a method overview section and more detailed description section for each method. The first sentence of any method description comment is included in the method overview section, with the complete text of the comment to be found in the detailed description section.

Although Javadoc ignores code implementation of constructors and methods, it does rely on javac to compile the declarations, i.e. the class and interface definitions as well as the method signatures. If no default constructor is defined, Javadoc will include it because the compiler indicates the default Object constructor is inherited by your class [10].

Javadoc works just as well on an abstract class as it does on a class definition that may be instantiated into objects. It makes no difference to the compiler run by Javadoc whether you have implemented your code fully. In this way Javadoc supports documentation and coding in any order.

Javadoc assembles hierarchical relationships between packages, interfaces, and classes, creating HTML pages from a standard style sheet (.css file) if none is specified. For more information on style sheets, refer to a very good introduction from CNET [1].

Java Code Comments

Simple Comments

Although programming languages are composed of a small set of keywords and strict syntax; sometimes source code is difficult to understand, even to someone very familiar with the language. Programmers make their code easier to understand simply by taking advantage of descriptive variable names, but that is not enough. This is where code documentation comes into play. Comments provide a person reading unfamiliar code a clearer idea about the intentions of the original programmer [4].

Java supports two styles of explicit comments. The first style is the traditional C comment, where characters between the start comment mark /* and the end comment mark */ are considered a comment and ignored by the compiler.

     
results.print(System.out); 	/* Send answers to standard output. */
      
problems.print(System.err); 	/* Send errors to error channel. */

The second type of comment comes from C++, where characters between the start comment mark // and the end of that line are ignored by the compiler and considered a comment [2].

     
results.print(System.out);      //Send answers to standard output.
   
     problems.print(System.err);     //Send errors to error channel.
      
Often it is quite useful to have a comment block, which spans many lines of code. In this case you can make your many line comment from C or C++ style comments. Have a look at the following code that demonstrates both techniques.
 
/* Here we print the answer of the computer's joke: 
   hard calculations of the meaning of life, etc. */

   int ultimateAnswer = 42;

   System.out.println ("The ultimate answer: " + ultimateAnswer);

   System.out.println ("\nSorry, we were just kidding there."); 
   					// Is the computer really sorry for

   System.out.println ("Some computers have ego problems and");  
   					// its mistake? I think if it was it
 
   System.out.println ("have a rather loose grip on reality."); 
    					// should make us cookies or something.

Understand that the above examples should not to be included in your code. Their emphasis is on the format of the comments rather than their content. While we're on that subject...

Avoiding Bad Comments

First, be careful not to accidentally comment out useful code with a poorly considered C style comment block:

     System.out.println(firstString); /* Print two strings 
     System.out.println(otherString);    to standard output. */
Only the first of the intended two commands will actually be executed. You see the problem, right? Our programmer accidentally wrapped the comment block around his or her second command. A C++ style comment block would have been much more appropriate.

Generally, an even marginally useful code comment is better than none at all, but there are always extreme cases that are exceptions to the rule. The following are two great examples of how not to comment your code.

 
     studentCounter++;   // increment the variable that counts the students
Unless the person reading the code has a bare minimum of programming experience, the comment on this line accomplishes nothing by over explaining simple syntax. Assume someone reading your comments knows the language.

      maximum = (number1 >number2) ? index1 : index2;   /* choose one */
This second horrible comment is more ambiguous than the statement itself, just making things worse.

Brian W. Kernighan and Rob Pike have some excellent suggestions for writing comments. They are said best as they appear in "The Practice of Programming," [3]:

Javadoc Comments

Now that the tedious background of good comment writing is out of the way, you are ready to write comments for Javadoc. To generate automatic HTML documentation using Javadoc, comments must be written in a special variation of the C style, with special predefined "Javadoc tags" that describe the signature of methods and other features of your code. Comment blocks written for inclusion in Javadoc HTML look like this:

import java.util.Random;

/**
 * A simple class to generate random integer arrays,
 * often quite useful for testing sorting algorithms.
 *
 * <p>
 * Written as an example for an ACM Crossroads article
 * about using <code>javadoc</code>, the Java API
 * documentation generator of HTML pages.
 *
 * @author    Kevin Henry <khenry@ece.villanova.edu>
 *
 * @link      http://www.acm.org/crossroads/
 * @link      http://www.ece.vill.edu/~khenry/javadoc/
 *
 * @see       java.lang.Integer
 *
 * @version   0.1
 */
public class GenerateIntArray
{
   /**
    * Create an array of primitive int values. Accept specified
    * number of values to generate, and an inclusive range within
    * which the generated values should fall.
    *
    * <p>
    * This is a trivial method written just to demonstrate how a 
    * comment is written for Javadoc. Notice the special tags:
    *
    * @since   0.1
    *
    * @param   size   the size of the array to create 
    *                 (the number of values to generate)
    * @param   min    the least value that may be generated
    * @param   max    the greatest value that may be generated
    *
    * @return         an array of <code>size</code> primitive int
    *                 values between the <code>min</code> and
    *                 <code>max</code> range, inclusive
    */
   public int [] generateRandomIntArray (int size, int min, int max)
   {
      Random generate = new Random ();
      int [] array = new int [size];
      for (int index = 0; index < size; index++)
         array [index] = generate.nextInt (max - min + 1) + min;
      return array;
   }
}
If your comment blocks follow the above style, Javadoc will notice them and create the appropriate HTML for the Java code. See the java output. Notice especially that HTML was included for a default constructor (NOTE: none of the links on that page work!). This is a result of Javadoc invoking part of javac.

You can use most standard HTML tags within your Javadoc comment blocks. Javadoc can understand and include standard HTML, it generates Web pages after all. Still, keep in mind that it's not a good idea to use tags like <h2></h2> in your comments. Javadoc will include them, but your browser may become confused when it tries to display the resulting pages because Javadoc inserts it own headings and yours will interfere with them.
@author Specifies which organization(s) and/or individual(s) were responsible for creating this class or interface.
@version Indicates the revision level of this Java code. Very useful during development or compatibility checking.
@param Describes the name and data type of the formal parameter being passed into the method as an argument.
@return Describes the data type being returned from the method, unless void when the tag is not included.
@since Tracks method additions within an evolving class or interface. Again, very useful for compatibility checking.
@exception Describes and links to any checked exceptions. These tags are synonymous as of Java 1.2.
@throws
@see Describes and links to other pages of interest related to this item. See the bug note below.
@link

The above example code also shows the most common Javadoc tags and where you are most likely to use them. The following table summarizes these Javadoc tags. For more information about the Javadoc tags, see the Javadoc Home Page [10], Javasoft's page of style suggestions for commenting code with Javadoc [5], or Sun Microsystems' How To Write Comments for Javadoc [8].

Making HTML From Java Source Code

Using the command line interface to the SDK, you can invoke the javadoc tool in a similar way as you invoke javac or java to compile and execute your programs.
      
     c:\programs> javadoc org.acm.crossroads MySimpleProgram.java
This command will generate and link HTML documentation for the classes found in the package org.acm.crossroads and in the source code file MySimpleProgram.java. Package names and source code file names may be given to Javadoc in any order.

You may notice that the standard Java API documentation is nicely linked together. That is, where one class takes a String as a parameter, a link appears so someone browsing the documentation can follow to learn more about that class. Unless you tell Javadoc to link your HTML documentation to the standard Java API, your pages will have no links, just parameters listed as java.lang.String. Your classes probably rely heavily on the standard Java API or some others, so to link documentation together do the following (when invoking javadoc, keep the entire command on one line, for readability this line is split):

      
c:\programs> javadoc 
-link http://java.sun.com/products/jdk/1.3/docs/api/
-link http://www.somewhere.com/other-api/
org.acm.crossroads MySimpleProgram.java
You can link to Javadoc API posted anywhere on the Web. For example, if you have other API posted on your personal site, you can link your newest production by simply giving Javadoc the URL of your existing documentation. You can also link to HTML pages on disk, but the local links Javadoc creates for you may become dead if you later post your documentation to the Web.

There is also a sourcepath option available to the command line, which tells Javadoc where to look for the Java source code files it should parse to create the documentation. The Javadoc sourcepath default is the current command line directory, which is used as the base for all class and package source code files. Using the sourcepath option overrides the default.

It is worth mentioning that there is a bug in the Javadoc tool that prevents @see tags from linking properly. The text appears, but is not referenced properly or linked anywhere. The bug is discussed in more detail on Sun's pages of documentation for the tool [9]. In the example above, what should have been a link to the Integer class of the Java API Specification shows up as a plain text java.lang.Integer. The tool version 1.2 did indicate a problem by warning me it could not find that class.

As mentioned above, Javadoc works by calling javac on the source code files. If your code is not in proper Java syntax you will not be able to use Javadoc.

More Customizing with Doclets

Javadoc 1.3 includes the capability of further customizing the appearance of your automatically generated documentation. Up to this point we have only mentioned or worked with the standard doclet, the only style of Web page available to us for automatic generation. By creating your own set of classes that will parse Java source code and create HTML documentation, you can override the standard doclet and exercise more control over how your API documentation will look. For more information about this process, see the Doclet Overview provided by Sun [6].

Conclusion

Documentation of a software product is an important part of software engineering that requires careful thought, organization, and planning. Sun recently created a feature-loaded, extensible support package product for creating platform independent help systems for Java applets, components, applications, operating systems, and devices. For serious corporate or professional development, see their site for JavaHelp [11].

This article discussed Javadoc, a powerful tool for easily creating professional looking documentation. Hopefully, this article helped you to realize the usefulness of Javadoc and will provide guidance for your upcoming projects.

References

1
CNET, Web Authoring. Getting Started With Cascading Style Sheets.
2
Deitel and Deitel. C++ How To Program, 2nd edition. Prentice Hall.
3
Kernighan, Brian W. and Pike, Rob, The Practice of Programming, Addison Wesley, 1999, pages 23-27.
4
Lewis and Loftus. Java Software Solutions: Foundations of Program Design, 2nd edition. Addison Wesley.
5
Javasoft. Conventions of Javadoc Comment Style.
6
Sun Microsystems. Doclet Overview.
7
Sun Microsystems. How To Write Comments for Javadoc.
8
Sun Microsystems. Java 1.3 API Specification.
9
Sun Microsystems, javadoc. The Java API Document Generator.
10
Sun Microsystems. Javadoc Tool Home Page.
11
Sun Microsystems. JavaHelp Product.

© Copyright 2000 by ACM, Inc.

Last Modified:
Location: www.acm.org/crossroads/columns/ovp/august2000.html

Page hits since August 24, 2000: