CMUQ 15-121 Javadoc



1. Introduction

One often neglected task among programmers is documentation of their code. We are often operating under tight deadlines, and as such don’t take the time to write up good documentation for the code we write. The advantages of good documentation are numerous:

The problem with documentation is that it takes time to write and frequently goes out of date. Imagine if, every time you changed something about a data structure you maintain you also had to go and edit the documentation about that data structure and make sure it reflects your updates, too. As you can guess, many programmers don’t bother to update the documentation and thus it quickly becomes stale and useless.

In this set of notes we’ll discuss Javadoc, which is Java’s method of writing documentation for code inside the code itself. By putting the documentation inside the code, it is easier for programmers to maintain (and frequently happens automatically).

2. Javadoc

Javadoc is basically a standardized way of writing comments for classes and methods so that a seperate tool (the javadoc tool) can analyze the source code (including those comments) and automatically generate HTML files containing documentation. This means that as long as the programmer keeps those comments up to date, he/she can generate the documentation automatically.

You’ve already benefited from Javadoc: The Java API documentation that has been frequently linked in these notes is automatically generated by the javadoc tool analyzing the source code for the Java API.

2.1. Comments

So far, in Java, we’ve seen two ways to write comments:

// This is a single link comment.

/* This is
 * a multi-line
 * comment.
 */

Javadoc comments are a slightly modified version of a multi-line comment:

/** 
 * This is a javadoc comment.
 * They can be multiple lines.
 * Notice the extra star on the opening comment line.
 */

Javadoc comments, when formatted correctly, are automatically picked up by javadoc and used to generate HTML documentation.

2.2. Example

The easiest way to be introduced to Javadoc is by example. Consider the following class file, including some basic Javadoc comments:

import java.io.FileReader;
import java.util.Random;
import java.util.Scanner;

/**
 * A basic hangman game. It reads words from a file, chooses one at random, and
 * then the player can guess letters one at a time until they get the word.
 * 
 * @author Joe Student
 * @version 1.0
 *
 */
public class Hangman {
    String word;
    String guesses;

    /**
     * Allocates a new hangman game. Reads in the list of possible words, and
     * chooses one at random.
     * 
     * @param length The minimum word length to consider. The chosen word with have
     *               a length >= this.
     */
    public Hangman(int length) {
        String words[] = new String[22000];
        int wc = 0;

        // Read in all the words
        Scanner wordFile = getFileScanner("words.txt");
        while (wordFile.hasNextLine()) {
            String word = wordFile.nextLine();
            if (word.length() >= length) {
                words[wc++] = word;
            }
        }

        wordFile.close();

        // Chose one at random
        Random r = new Random();
        word = words[r.nextInt(wc)];

        // Initialize the guesses
        guesses = "";
    }

    /**
     * Build a "blinded" copy of the word being guessed. This combines the word
     * itself along with the guesses to produce a copy of the word with only the
     * guessed letters present and _ in place of unguessed letters.
     * 
     * @return The blinded word.
     */
    public String getWord() {
        String ret = "";

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (guesses.indexOf(c) >= 0) {
                ret += c;
            } else {
                ret += "_";
            }
            ret += " ";
        }

        return ret;
    }

    /**
     * Play the game. This method is interactive, continually asking the player to
     * guess a letter and updating the word appropriately.
     */
    public void play() {
        Scanner inp = new Scanner(System.in);
        System.out.println("Welcome to hangman!");

        while (true) {
            System.out.println("The word is " + getWord());
            System.out.println("You have guessed: " + guesses);
            System.out.print("Next guess? ");
            String guess = inp.nextLine();
            guesses += guess;
        }

    }

    /**
     * A helper method to open a file and return a Scanner to it.
     * 
     * @param filename The filename of the file to open
     * @return A Scanner object to the open file, or null if the file could not be
     *         opened.
     */
    private static Scanner getFileScanner(String filename) {
        Scanner myFile;
        try {
            myFile = new Scanner(new FileReader(filename));
        } catch (Exception e) {
            System.out.println("File not found: " + filename);
            return null;
        }
        return myFile;
    }

    /**
     * A simple main to create a new Hangman game and play it.
     * 
     * @param args Command line arguments. (Unused.)
     */
    public static void main(String args[]) {
        Hangman game = new Hangman(5);
        game.play();
    }
}

As you can see, the Javadoc comments also have key words (like @author, @version, @param, @return, etc.) These are used to specify specific things about the class or method being documented. In Eclipse, if you start writing a Javadoc comment (by typing /** and pressing enter) it will generate an empty comment with useful keywords for you to fill-in.

In the case of the example above, if I run the javadoc tool (by going to Project -> Generate Javadoc in Eclipse) then I would get the following generated documentation:

Javadoc Documentation for Hangman

3. More Information

For more information about writing Javadoc comments, try the following resources: