Creating Self-Documenting Java Code Using Javadocs

Everybody knows that developers hate to write documentation (except for me, I'm apparently some sort of mutant), especially detailed documentation for the code that they create. The problem is that documentation is important.

A typical software project may be created over a period of months but will often have a lifetime of years. During this lifetime, software will spend considerably more time in maintenance than it will in development. It's almost inevitable that over time turnover will result in the software being maintained by people other than the original developers, and often less technically capable as well.

Helping the Maintainers

Documentation is the key to ensuring that a software project is maintained properly and effectively throughout the software lifecycle. However, there are different types of documentation, which are useful to varying degrees.

First, there are project-level documents, such as requirements documents and design documents. These are generally useful during the original software development phase, but are rarely kept up-to-date with subsequent changes. As a result, they tend to age badly and become decreasingly useful in supporting maintenance activities. They also have a tendency to become separated from the source code, so that maintainers may not even be able to find them (which is why I also advocate that such documents be stored in the same repository as the source code).

Second, maintainers may be assisted by documentation embedded in the source code files themselves. Such documentation may take the form of the usual intermittent developer comments or, even better, well-organized documentation blocks for items such as classes and functions.

Well-organized, embedded docuemntation can be the best asset available to assist maintainers in supporting a software project. As might be expected, there are tools that support the creation of embedded documentation. Javadoc is a tool for supporting embedded documentation in Java projects.

What is Javadoc?

Javadoc is a tool created by Sun Microsystems that allows users to easily define documentation blocks in their Java source code, in the form of comments that follow simple Javadoc conventions. These comments can be automatically extracted to produce detailed code-level documentation in HTML for easy viewing.

There are some significant advantages to embedded documentation. Comment blocks can be created as needed during the development process (rather than in some last-minute big-bang documentation frenzy). As source code is changed, it's easy for developers to update the documentation; after all, the comments are right there next to the code being changed. And as long as the source code doesn't get lost, neither will the embedded documentation.

Furthermore, Javadoc supports the automated extraction of properly formatted comments. Javadoc can easily extract all of the embedded documentation and organize it into a well-structured set of HTML pages that makes it easy to navigate and view the documentation.

Embedded documentation is by no means a new concept. My first recollection of an organized mechanism for embedded documentation is Perl. There are also similar features for ASP.NET (C# and VB.NET), Ruby and other languages.

Formatting a Javadoc Comment Block

The key phrase that developers worry about when they first hear about Javadoc is that whole thing about "properly formatted comments." So, yes, in order to use Javadoc, you must format your comments in a specific manner and also make use of certain keywords. This is necessary so that the comments, and even some of the specific sub-components within comment blocks, can be extracted effectively.

Fortunately, the special formatting required for Javadoc is trivial, as is illustrated in Listing 1 below, which was pulled from a real project. For brevity, only the class comment block and a representative method are shown.

Listing 1: Sample Code with JavaDocs

 * The Operation class represents a task, or operation,
 * to be accomplished. An operation is stored in the
 * database for eventual execution; the database allows
 * all required information necessary to complete a task
 * to be stored in the database along with the standard
 * elements of an operation, such as the type of operation,
 * the status, arguments, etc.
 * <p>An operation is executed when a daemon, referred
 * to as the Op Handler, retrieves data about an operation
 * from the database and executes a program in order to
 * accomplish the task represented by the operation.

public class Operation

 * This static method reads in the complete list of operations,
 * only excluding operations that have been marked as deleted
 * (marked inactive). This version of the method allows the
 * caller to specify a filter string, a set of AND clauses
 * for the SQL statement, to modify the results that
 * would be returned by the underlying query. Callers may
 * also control ordering by including an ordering clause.
 * @param  DBConnection The database connection.
 * @param  strFilter    A filter string, or a set of AND clauses,
 *                     to filter the result set so that it
 *                     only includes desired results.
 * @param  strOrderBy   A string that defines an ORDER BY
 *                     clause for the SQL statement that
 *                     returns operations. If NULL, operations
 *                     will be ordered in ascending
 *                     order by operation ID.
 * @return             Returns an ArrayList of Operation
 *                     objects, or NULL if the list could
 *                     not be retrieved.

 public static ArrayList readList(DBConnection rmcon,
    String strFilter,      String strOrderBy)
    // Real code would appear here
 } // End Method

} // End Class

I've led numerous development teams in my career. For my Java projects, Figure 1 shows all of the elements that I require my developers to put in their comments. However, please note that I don't recommend comment blocks for simple getter/setter methods (documenting getters and setters won't really be useful and developers will hate you if you make them do that).

So. let's take a closer look at Listing 1. It's pretty easy to identify a Javadoc comment block because they look like:

     * Content

Any comment block that appears before the class declaration (or interface declaration, etc.) is a class-level comment. Any comment block that appears within a class and before a method declaration is a method comment block. For additional formatting, simple HTML tags can also be included in a comment block (generally paragraph tags, lists, etc). That's pretty easy.

Also, note that the first sentence of a comment blcok for a class or method is special. The first sentence should be a concise summary of the class or method. The first sentence will be used by Javadoc as a short description of the object, and will appear on summary pages where multiple classes or methods may be listed.

Javadoc keywords begin with the "@" symbol. So, "@param" describes a method parameter, where the first word after the keyword is the name of the parameter and any additional text is a description. Likewise, the "@return" keyword describes the return value of a method. Spacing is unimportant to Javadoc, so the neat formatting shown in Listing 1 was done based on team preferences, but any reasonable formatting would be fine.

These keywords allow Javadoc to easily extract this information to include in the generated HTML documentation. It's customary to leave out these keywords if a method doesn't have any parameters or doesn't have a return value.

That's it. That's all you need to do in order to have embedded documentation in your source code.

Of course, Javadoc does have more advanced features but, frankly, the basic formatting described in this section will provide you with 95% of the benefits that are achievable with Javadocs, and without requiring professional documentation specialists.

Generating HTML Documentation

The HTML output generated by Javadoc will look something like the sample output shown in Figure 1. With this multiple-panel format, users can easily navigate the class structure of a project and drill down to view detailed information.

Javadoc in action - A typical Overview page

So, how to you actually generate the HTML documentation? Listing 2 shows a simple Korn shell script that generates documentation from a source code tree using the Javadoc tool.

Listing 2 - Generating Javadoc Documentation


if [ -e ${JAVADOC_DIR} ]
   echo "Deleting java doc directory: ${JAVADOC_DIR}"
   rm -rf ${JAVADOC_DIR}

# Create directory for generated javadocs
mkdir -p ${JAVADOC_DIR}

JAVA_FILES=$(find ${SRC_DIR} -name "*.java")

echo "Generating javadoc files"

echo "Completed javadocs generation"

This shell script requires that the following environment variables be set:

  • CLASS_PATH: The class path defines where the javadoc compiler can find all of the libraries required to compile the Java code. The Javadoc tool needs to use the same libraries as the Java compiler.

  • JAVADOC_DIR: The directory in which generated Javadoc files should be deposited when the Javadoc tool is executed. Necessary for the shell script.

  • JAVA_HOME: The location of the bin diretcory for the local Java installation. Necessary for the shell script.

  • SRC_DIR: The top-level directory of the source code tree from which embedded Javadoc comments will be extracted and converted into HTML documentation. Necessary for the shell script.

It's possible to generate Javadoc documentation with only a few lines of shell script. Enterprising developers could even tune this shell script to better support a development group. On one of my recent teams, we generated the Javadocs every time we built the project, and deposited the documentation in a sub-directory of the web site we were creating. Thus, the current documentation was available in every single one of our development environments.

Other Useful Javadoc Keywords

There are a variety of keywords that can be used in projects. In general, I've found that most developers seldom use them. For the sake of completeness, other keywords include:

  • @author: Defines the name of the author of the source file. Can occur multiple times (chronological order is preferred, if used). In my experience, this has seldom been used.

  • @deprecated: This keyword is used to designate a class or method as deprecated. This is sometimes used.

  • @exception: Deprecated. Use @throws instead.

  • @link: Allows you to generate links within the Javadocs documentation. Generally seems to be more trouble than it's worth in practice. Plus, who wants to try to keep the links in sync as code changes?

  • @see: This keyword refers a user to another item in the documentation, generally a similar class or method. Useful for pointing out references to readers, but seldom used in practice by developers.

  • @serial: This is advanced Javadocs. I've never seen it used. If you think you need to use it, check out the references at the end of this article.

  • @since: Allows a developer to specify what version of an API a feature was added in. Um, not too useful unless you're writing a commercial or open source API for use by a large number of other developers.

  • @throws: This keyword is used to record any exceptions that a method may throw. Most developers forget to use it.

  • @version: Used to include the version within the generated documentation. In practice, I've never used this keyword.

Consult the Javadoc references at the end of this article if you need to use some of these keywords.


I'm a professional developer, and the source code that I produce, whether created directly by myself or created by a team that I'm leading, is my product. I want that product to be as good as it can be. I want that product to serve my clients well and last as long as possible. To me, a vital aspect of my product is maintainability. Javadoc is a key tool in creating maintainable Java code. It's so simple to use, it's almost unprofessional not to use it.


There are a number of relevant references available online concerning Javadoc:


No comments yet. Be the first.

Leave a Comment

Comments are moderated and will not appear on the site until reviewed.

(not displayed)