Using Java Documentation Comments


In this article, we will discuss how to write Java documentation comments and how to use Javadoc tags in documentation comments.
Java supports three types of comments:
  1. Single Line Comment
 //text
The compiler ignores everything from // to the end of the line.
  1. Multi-Line Comment
/* text */
The compiler ignores everything from /* to */.
  1. Documentation Comment
/** documentation */
Documentation comments allow you to embed information about your program into the program itself. You can then use the Javadoc utility program (supplied with the JDK) to extract the information and put it into an HTML file.
Documentation comments make it convenient to document your programs. You have almost certainly seen documentation generated with Javadoc because that is the way the Java API library was documented.

Learn complete Java programming language at Java Tutorial | Learn Java Programming with Examples.

Usage of three types of comments example

Below example demonstrates usage of all 3 types of comments:
package com.javaguides.corejava;

/**
 * First Java Helloworld Program.
 * @author Ramesh Fadatare
 * @version 1.8
 * @since 2018
 */
public class HelloWorld {

    /*
     * main() method is entry point of the program.
     * JVM searches for main() method
     */
    public static void main(String[] args) {

        // Prints Hello world string to console
        System.out.println("Hello world");
    }
}
Output:
Hello world

Example from JDK Library

Notice here, how the documentation comments are implemented in Runnable interface from JDK 8 library.
package java.lang;

/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

What is Javadoc?

Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code, which requires documentation in a predefined format.

The Javadoc Tags

The Javadoc utility recognizes the following tags:
Document tags that begin with an “at” sign (@) are called stand-alone tags (also called block tags), and they must be used on their own line. Tags that begin with a brace, such as {@code}, are called in-line tags, and they can be used within a larger description. You may also use other, standard HTML tags in a documentation comment Let's learn more about Java code documentation comments.

The General Form of a Documentation Comment

After the beginning /**, the first line or lines become the main description of your class, interface, field, constructor, or method. After that, you can include one or more of the various @ tags. Each @ tag must start at the beginning of a new line or follow one or more asterisks (*) that are at the start of a line.
Multiple tags of the same type should be grouped together. For example, if you have three @see tags, put them one after the other. In-line tags (those that begin with a brace) can be used within any description.
Here is an example of a documentation comment for a class:
/**
 * First Java Helloworld Program.
 * @author Ramesh Fadatare
 * @version 1.8
 * @since 2018
 */
public class HelloWorld {

      public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

What Javadoc Outputs

The Javadoc program takes as input your Java program’s source file and outputs several HTML files that contain the program’s documentation. Information about each class will be in its own HTML file. javadoc will also output an index and a hierarchy tree. Other HTML files can be generated.

An Example that Uses Documentation Comments

Following is a sample program that uses documentation comments. Notice the way each comment immediately precedes the item that it describes. After being processed by Javadoc, the documentation about the a SquareNum class will be found in SquareNum.html.
/**
 * This class demonstrates documentation comments.
 * 
 * @author Ramesh Fadatare
 * @version 1.8
 */
public class SquareNum {
    /**
     * This method returns the square of num. This is a multiline description. You
     * can use as many lines as you like.
     * 
     * @param num The value to be squared.
     * @return num squared.
     */
    public double square(double num) {
        return num * num;
    }

    /**
     * This method inputs a number from the user.
     * 
     * @return The value input as a double.
     * @exception IOException On input error.
     * @see IOException
     */
    public double getNumber() throws IOException {
        // create a BufferedReader using System.in
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader inData = new BufferedReader(isr);
        String str;
        str = inData.readLine();
        return (new Double(str)).doubleValue();
    }

    /**
     * This method demonstrates square().
     * 
     * @param args Unused.
     * @exception IOException On input error.
     * @see IOException
     */
    public static void main(String args[]) throws IOException {
        SquareNum ob = new SquareNum();
        double val;
        System.out.println("Enter value to be squared: ");
        val = ob.getNumber();
        val = ob.square(val);
        System.out.println("Squared value is " + val);
    }
}
Output:
Enter value to be squared: 
2
Squared value is 4.0

Javadoc Generation

In order to generate our Javadoc pages, we’ll want to take a look at the command line tool that ships with the JDK, and the Maven plugin.

Javadoc Command Line Tool

The javadoc command line tool is very powerful but has some complexity attached to it.
Running the command javadoc without any options or parameters will result in an error and output parameters it expects.
We’ll need to at least specify what package or class we want documentation to be generated for.
Let’s open a command line and navigate to the project directory.
Assuming the classes are all in the src folder in the project directory:
$ javadoc -d documentation src\*
This will generate documentation in a directory called documentation folder as specified with the –d flag. If multiple packages or files exist, we’d need to provide all of them.

Javadoc With Maven Plugin

We can also make use of the Maven Javadoc plugin:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
            <tags>
            ...
            </tags>
        </plugin>
    </plugins>
</build>
In the base directory of the project, we run the command to generate our Javadocs to a directory in target\site:
$ mvn javadoc:javadoc

The Maven plugin is very powerful and facilitates complex document generation seamlessly.
Learn complete Java programming language at Java Tutorial | Learn Java Programming with Examples.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments