How to write javadoc
How to write javadoc
CONTENTS
Reference Guide
SYNOPSIS
DESCRIPTION
Conformance
For more information about conformance requirements for HTML5 documents, see Conformance requirements in the HTML5 specification. For more information about security issues related to web pages, see Open Web Application Security Project (OWASP).
Processing of source files
As implemented, the Javadoc tool requires and relies on the java compiler to do its job. The Javadoc tool calls part of javac to compile the declarations, ignoring the member implementation. It builds a rich internal representation of the classes, including the class hierarchy, and «use» relationships, then generates the HTML from that. The Javadoc tool also picks up user-supplied documentation from documentation comments in the source code.
In many cases, the Javadoc tool allows you to generate documentation for source files whose code is incomplete or erroneous. This is a benefit that enables you to generate documentation before all debugging and troubleshooting is done. For example, according to the Java Language Specification, a class that contains an abstract method should itself be declared abstract. The Javadoc tool does not check for this, and would proceed without a warning, whereas the javac compiler stops on this error. The Javadoc tool does do some primitive checking of doc comments. Use the DocCheck doclet to check the doc comments more thoroughly.
When the Javadoc tool builds its internal structure for the documentation, it loads all referenced classes. Because of this, the Javadoc tool must be able to find all referenced classes, whether bootstrap classes, extensions, or user classes. For more about this, see How Classes Are Found. Generally speaking, classes you create must either be loaded as an extension or in the Javadoc tool’s class path.
Javadoc Doclets
Related Documentation and Doclets
Terminology
documented classes The classes and interfaces for which detailed documentation is generated during a javadoc run. To be documented, the source files must be available, their source filenames or package names must be passed into the javadoc command, and they must not be filtered out by their access modifier (public, protected, package-private or private). We also refer to these as the classes included in the javadoc output, or the included classes.
included classes Classes and interfaces whose details are documented during a run of the Javadoc tool. Same as documented classes.
excluded classes Classes and interfaces whose details are not documented during a run of the Javadoc tool.
SOURCE FILES
Class Source Code Files
Package Comment Files
To create a package comment file, you have a choice of two files to place your comments:
Generates HTML pages of API documentation from Java source files. This document contains Javadoc examples for Solaris.
CONTENTS
Reference Guide
SYNOPSIS
DESCRIPTION
The Javadoc tool parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields. You can use it to generate the API (Application Programming Interface) documentation or the implementation documentation for a set of source files.
Conformance
For more information about conformance requirements for HTML5 documents, see Conformance requirements in the HTML5 specification. For more information about security issues related to web pages, see Open Web Application Security Project (OWASP).
Processing of source files
As implemented, the Javadoc tool requires and relies on the java compiler to do its job. The Javadoc tool calls part of javac to compile the declarations, ignoring the member implementation. It builds a rich internal representation of the classes, including the class hierarchy, and «use» relationships, then generates the HTML from that. The Javadoc tool also picks up user-supplied documentation from documentation comments in the source code.
In many cases, the Javadoc tool allows you to generate documentation for source files whose code is incomplete or erroneous. This is a benefit that enables you to generate documentation before all debugging and troubleshooting is done. For example, according to the Java Language Specification, a class that contains an abstract method should itself be declared abstract. The Javadoc tool does not check for this, and would proceed without a warning, whereas the javac compiler stops on this error. The Javadoc tool does do some primitive checking of doc comments. Use the DocCheck doclet to check the doc comments more thoroughly.
When the Javadoc tool builds its internal structure for the documentation, it loads all referenced classes. Because of this, the Javadoc tool must be able to find all referenced classes, whether bootstrap classes, extensions, or user classes. For more about this, see How Classes Are Found. Generally speaking, classes you create must either be loaded as an extension or in the Javadoc tool’s class path.
Javadoc Doclets
You can customize the content and format of the Javadoc tool’s output by using doclets. The Javadoc tool has a default «built-in» doclet, called the standard doclet, that generates HTML-formatted API documentation. You can modify or subclass the standard doclet, or write your own doclet to generate HTML, XML, MIF, RTF or whatever output format you’d like. Information about doclets and their use is at the following locations:
When a custom doclet is not specified with the -doclet command line option, the Javadoc tool will use the default standard doclet. The javadoc tool has several command line options that are available regardless of which doclet is being used. The standard doclet adds a supplementary set of command line options. Both sets of options are described below in the options section.
Related Documentation and Doclets
Terminology
The terms documentation comment, doc comment, main description, tag, block tag, and in-line tag are described at Documentation Comments. These other terms have specific meanings within the context of the Javadoc tool:
generated document The document generated by the javadoc tool from the doc comments in Java source code. The default generated document is in HTML and is created by the standard doclet.
documented classes The classes and interfaces for which detailed documentation is generated during a javadoc run. To be documented, the source files must be available, their source filenames or package names must be passed into the javadoc command, and they must not be filtered out by their access modifier (public, protected, package-private or private). We also refer to these as the classes included in the javadoc output, or the included classes.
included classes Classes and interfaces whose details are documented during a run of the Javadoc tool. Same as documented classes.
excluded classes Classes and interfaces whose details are not documented during a run of the Javadoc tool.
SOURCE FILES
Class Source Code Files
Package Comment Files
Each package can have its own documentation comment, contained in its own «source» file, that the Javadoc tool will merge into the package summary page that it generates. You typically include in this comment any documentation that applies to the entire package.
To create a package comment file, you have a choice of two files to place your comments:
Note that while the comment separators /** and /* must be present, the leading asterisks on the intermediate lines can be omitted.
How to Write Doc Comments for the Javadoc Tool
This document describes the style guide, tag and image conventions we use in documentation comments for Java programs written at Java Software, Sun Microsystems. It does not rehash related material covered elsewhere:
Contents
Introduction
Writing Doc Comments
Introduction
Principles
At Java Software, we have several guidelines that might make our documentation comments different than those of third party developers. Our documentation comments define the official Java Platform API Specification. To this end, our target audience is those who write Java compatibility tests, or conform or re-implement the Java platform, in addition to developers. We spend time and effort focused on specifying boundary conditions, argument ranges and corner cases rather than defining common programming terms, writing conceptual overviews, and including examples for developers.
Writing API Specifications
Notice that the specification does not need to be entirely contained in doc comments. In particular, specifications that are lengthy are sometimes best formatted in a separate file and linked to from a doc comment.
The Specification describes all aspects of the behavior of each method on which a caller can rely. It does not describe implementation details, such as whether the method is native or synchronized. The specification should describe (textually) the thread-safety guarantees provided by a given object. In the absence of explicit indication to the contrary, all objects are assumed to be «thread-safe» (i.e., it is permissible for multiple threads to access them concurrently). It is recognized that current specifications don’t always live up to this ideal.
This means that the doc comments must satisfy the needs of the conformance testing by SQA. The comments should not document bugs or how an implementation that is currently out of spec happens to work.
Writing Programming Guide Documentation
It’s useful to go into further detail about how to document bugs and workarounds. There is sometimes a discrepancy between how code should work and how it actually works. This can take two different forms: API spec bugs and code bugs. It’s useful to decide up front whether you want to document these in the doc comments. At Java Software we have decided to document both of these outside of doc comments, though we do make exceptions.
API spec bugs are bugs that are present in the method declaration or in the doc comment that affects the syntax or semantics. An example of such a spec bug is a method that is specified to throw a NullPointerException when null is passed in, but null is actually a useful parameter that should be accepted (and was even implemented that way). If a decision is made to correct the API specification, it would be useful to state that either in the API specification itself, or in a list of changes to the spec, or both. Documenting an API difference like this in a doc comment, along with its workaround, alerts a developer to the change where they are most likely to see it. Note that an API specification with this correction would still maintain its implementation-independence.
Code bugs are bugs in the implementation rather than in the API specification. Code bugs and their workarounds are often likewise distributed separately in a bug report. However, if the Javadoc tool is being used to generate documentation for a particular implementation, it would be quite useful to include this information in the doc comments, suitably separated as a note or by a custom tag (say @bug ).
Who Owns and Edits the Doc Comments
The doc comments for the Java platform API specification is owned programmers. However, they are edited by both programmers and writers. It is a basic premise that writers and programmers honor each other’s capabilities and both contribute to the best doc comments possible. Often it is a matter of negotiation to determine who writes which parts of the documentation, based on knowledge, time, resources, interest, API complexity, and on the state of the implementation itself. But the final comments must be approved by the responsible engineer.
Ideally, the person designing the API would write the API specification in skeleton source files, with only declarations and doc comments, filling in the implementation only to satisfy the written API contract. The purpose of an API writer is to relieve the designer from some of this work. In this case, the API designer would write the initial doc comments using sparse language, and then the writer would review the comments, refine the content, and add tags.
If the doc comments are an API specification for re-implementors, and not simply a guide for developers, they should be written either by the programmer who designed and implemented the API, or by a API writer who is or has become a subject matter expert. If the implementation is written to spec but the doc comments are unfinished, a writer can complete the doc comments by inspecting the source code or writing programs that test the API. A writer might inspect or test for exceptions thrown, parameter boundary conditions, and for acceptance of null arguments. However, a much more difficult situation arises if the implementation is not written to spec. Then a writer can proceed to write an API specification only if they either know the intent of the designer (either through design meetings or through a separately-written design specification) or have ready access to the designer with their questions. Thus, it may be more difficult for a writer to write the documentation for interfaces and abstract classes that have no implementors.
With that in mind, these guidelines are intended to describe the finished documentation comments. They are intended as suggestions rather than requirements to be slavishly followed if they seem overly burdensome, or if creative alternatives can be found. When a complex system such as Java (which contains about 60 packages) is being developed, often a group of engineers contributing to a particular set of packages, such as javax.swing may develop guidelines that are different from other groups. This may be due to the differing requirements of those packages, or because of resource constraints.
Terminology
API documentation (API docs) or API specifications (API specs)
On-line or hardcopy descriptions of the API, intended primarily for programmers writing in Java. These can be generated using the Javadoc tool or created some other way. An API specification is a particular kind of API document, as described above. An example of an API specification is the on-line Java 2 Platform Standard Edition API Specifications. An example of an API document is the Java Class Libraries book by Chan/Lee.
Documentation comments (doc comments)
javadoc
The JDK tool that generates API documentation from documentation comments.
Source Files
The Javadoc tool can generate output originating from four different types of «source» files:
For more details, see: Source Files.
Writing Doc Comments
Format of a Doc Comment
Example
Notes:
For more examples, see Simple Examples.
So lines won’t wrap, limit any doc-comment lines to 80 characters.
Here is what the previous example would look like after running the Javadoc tool:
getImage
getImage( URL url, String name)
This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.
Parameters:
Returns:
the image at the specified URL
See Also:
Doc Comment Checking Tool
At Sun, we have developed a tool for checking doc comments, called the Sun Doc Check Doclet. You run it on source code and it generates a report describing what style and tag errors the comments have, and recommends changes. We have tried to make its rules conform to the rules in this document.
DocCheck is a Javadoc doclet, or «plug-in», and so requires that the Javadoc tool be installed (as part of the Java 2 Standard Edition SDK).
Descriptions
First Sentence
The first sentence of each doc comment should be a summary sentence, containing a concise but complete description of the API item. This means the first sentence of each member, class, interface or package description. The Javadoc tool copies this first sentence to the appropriate member, class/interface or package summary. This makes it important to write crisp and informative initial sentences that can stand on their own.
This sentence ends at the first period that is followed by a blank, tab, or line terminator, or at the first tag (as defined below). For example, this first sentence ends at «Prof.»:
However, you can work around this by typing an HTML meta-character such as «&» or » java.lang.Runtime :
On Windows systems, the path search behavior of the loadLibrary method is identical to that of the Windows API’s LoadLibrary procedure.
The use of «On Windows» at the beginning of the sentence makes it clear up front that this is an implementation note.
Automatic re-use of method comments
You can avoid re-typing doc comments by being aware of how the Javadoc tool duplicates (inherits) comments for methods that override or implement other methods. This occurs in three cases:
A Style Guide
The following are useful tips and conventions for writing descriptions in doc comments.
Our audience is advanced (not novice) programmers, so it is generally not necessary to link to API in the java.lang package (such as String), or other API you feel would be well-known.
Omit parentheses for the general form of methods and constructors
When referring to a method or constructor that has multiple forms, and you mean to refer to a specific form, use parentheses and argument types. For example, ArrayList has two add methods: add(Object) and add(int, Object).
The add(int, Object) method adds an item at a specified position in this arraylist.
However, if referring to both forms of the method, omit the parentheses altogether. It is misleading to include empty parentheses, because that would imply a particular form of the method. The intent here is to distinguish the general method from any of its particular forms. Include the word «method» to distinguish it as a method and not a field.
The add method enables you to insert items. | (preferred) |
The add() method enables you to insert items. | (avoid when you mean «all forms» of the add method) |
The description is in 3rd person declarative rather than 2nd person imperative.
A method implements an operation, so it usually starts with a verb phrase:
Gets the label of this button. | (preferred) |
This method gets the label of this button. | (avoid) |
A button label. | (preferred) |
This field is a button label. | (avoid) |
Gets the toolkit for this component. | (preferred) |
Gets the toolkit for the component. | (avoid) |
Add description beyond the API name. The best API names are «self-documenting», meaning they tell you basically what the API does. If the doc comment merely repeats the API name in sentence form, it is not providing more information. For example, if method description uses only the words that appear in the method name, then it is adding nothing at all to what you could infer. The ideal comment goes beyond those words and should always reward you with some bit of information that was not immediately obvious from the API name.
Tag Conventions
This section covers:
Most of the following tags are specified in the Java Language Specification, First Edition. Also see the Javadoc reference page.
Order of Tags
Include tags in the following order:
Ordering Multiple Tags
We employ the following conventions when a tag appears more than once in a documentation comment. If desired, groups of tags, such as multiple @see tags, can be separated from the other tags by a blank line with a single asterisk.
Multiple @author tags should be listed in chronological order, with the creator of the class listed at the top.
Multiple @param tags should be listed in argument-declaration order. This makes it easier to visually match the list to the declaration.
Multiple @throws tags (also known as @exception) should be listed alphabetically by the exception names.
Multiple @see tags should be ordered as follows, which is roughly the same order as their arguments are searched for by javadoc, basically from nearest to farthest access, from least-qualified to fully-qualified, The following list shows this progression. Notice the methods and constructors are in «telescoping» order, which means the «no arg» form first, then the «1 arg» form, then the «2 arg» form, and so forth. Where a second sorting key is needed, they could be listed either alphabetically or grouped logically.
Required Tags
These principles expedite automated searches and automated processing. Frequently, too, the effort to avoid redundancy pays off in extra clarity.
Tag Comments
As a reminder, the fundamental use of these tags is described on the Javadoc Reference page. Java Software generally uses the following additional guidelines to create comments for each tag:
You can provide one @author tag, multiple @author tags, or no @author tags. In these days of the community process when development of new APIs is an open, joint effort, the JSR can be consider the author for new packages at the package level. For example, the new package java.nio has «@author JSR-51 Expert Group» at the package level. Then individual programmers can be assigned to @author at the class level. As this tag can only be applied at the overview, package and class level, the tag applies only to those who make significant contributions to the design or implementation, and so would not ordinarily include technical writers.
The @author tag is not critical, because it is not included when generating the API specification, and so it is seen only by those viewing the source code. (Version history can also be used for determining contributors for internal purposes.)
If the author is unknown, use «unascribed» as the argument to @author. Also see order of multiple @author tags.
The Java Software convention for the argument to the @version tag is the SCCS string «%I%, %G%», which converts to something like » 1.39, 02/28/97 » (mm/dd/yy) when the file is checked out of SCCS.
Parameter names are lowercase by convention. The data type starts with a lowercase letter to indicate an object rather than a class. The description begins with a lowercase letter if it is a phrase (contains no verb), or an uppercase letter if it is a sentence. End the phrase with a period only if another phrase or sentence follows it.
When writing the comments themselves, in general, start with a phrase and follow it with sentences if they are needed.
@param x the x-coordinate, measured in pixels
@param x the x-coordinate. Measured in pixels.
@param x Specifies the x-coordinate, measured in pixels.
@param x Specifies the x-coordinate. Measured in pixels.
Omit @return for methods that return void and for constructors; include it for all other methods, even if its content is entirely redundant with the method description. Having an explicit @return tag makes it easier for someone to find the return value quickly. Whenever possible, supply return values for special cases (such as specifying the value returned when an out-of-bounds argument is supplied).
Use the same capitalization and punctuation as you used in @param.
The @deprecated description in the first sentence should at least tell the user when the API was deprecated and what to use as a replacement. Only the first sentence will appear in the summary section and index. Subsequent sentences can also explain why it has been deprecated. When generating the description for a deprecated API, the Javadoc tool moves the @deprecated text ahead of the description, placing it in italics and preceding it with a bold warning: «Deprecated». An @see tag (for Javadoc 1.1) or <@link>tag (for Javadoc 1.2 or later) should be included that points to the replacement method:
If the member has no replacement, the argument to @deprecated should be «No replacement».
Do not add @deprecated tags without first checking with the appropriate engineer. Substantive modifications should likewise be checked first.
Specify the product version when the Java name was added to the API specification (if different from the implementation). For example, if a package, class, interface or member was added to the Java 2 Platform, Standard Edition, API Specification at version 1.2, use:
The Javadoc standard doclet displays a «Since» subheading with the string argument as its text. This subheading appears in the generated text only in the place corresponding to where the @since tag appears in the source doc comments (The Javadoc tool does not proliferate it down the hierarchy).
(The convention once was » @since JDK1.2 » but because this is a specification of the Java Platform, not particular to the Sun JDK or SDK, we have dropped «JDK».)
When a package is introduced, specify an @since tag in its package description and each of its classes. (Adding @since tags to each class is technically not needed, but is our convention, as enables greater visibility in the source code.) In the absence of overriding tags, the value of the @since tag applies to each of the package’s classes and members.
When a class (or interface) is introduced, specify one @since tag in its class description and no @since tags in the members. Add an @since tag only to members added in a later version than the class. This minimizes the number of @since tags.
If a member changes from protected to public in a later release, the @since tag would not change, even though it is now usable by any caller, not just subclassers.
@throws ( @exception was the original tag) (reference page)
See the Exceptions chapter of the Java Language Specification, Second Edition for more on exceptions. Also see order of multiple @throws tags.
For information about how to use these tags, along with an example, see «Documenting Serializable Fields and Data for a Class,» Section 1.6 of the Java Object Serialization Specification. Also see Sun’s criteria for including classes in the serialized form specification.
(Added in Javadoc 1.2)
Custom Tags and Annotations
If annotations are new to you, when you need to markup your source code, it might not be immediately clear whether to use an annotation or a Javadoc custom tag. Here is a quick comparison of the two.
In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.
If you need to affect both program semantics and documentation, you probably need both an annotation and a tag. For example, our guidelines now recommend using the @Deprecated annotation for alerting the compiler warning and the @deprecated tag for the comment text.
Documenting Default Constructors
Section 8.8.7 of the Java Language Specification, Second Edition describes a default constructor: If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided. It invokes the superclass constructor with no arguments. The constructor has the same access as its class.
Good programming practice dictates that code should never make use of default constructors in public APIs: All constructors should be explicit. That is, all default constructors in public and protected classes should be turned into explicit constructor declarations with the appropriate access modifier. This explicit declaration also gives you a place to write documentation comments.
The reason this is good programming practice is that an explicit declaration helps prevents a class from inadvertently being made instantiable, as the design engineer has to actually make a decision about the constructor’s access. We have had several cases where we did not want a public class to be instantiable, but the programmer overlooked the fact that its default constructor was public. If a class is inadvertently allowed to be instantiable in a released version of a product, upward compatibility dictates that the unintentional constructor be retained in future versions. Under these unfortunate circumstances, the constructor should be made explicit and deprecated (using @deprecated ).
Note that when creating an explicit constructor, it must match precisely the declaration of the automatically generated constructor; even if the constructor should logically be protected, it must be made public to match the declaration of the automatically generated constructor, for compatibility. An appropriate doc comment should then be provided. Often, the comment should be something as simple as:
Documenting Exceptions with @throws Tag
Documenting Exceptions in API Specs
Throws Tag
The purpose of the @throws tag is to indicate which exceptions the programmer must catch (for checked exceptions) or might want to catch (for unchecked exceptions).
Document the following exceptions with the @throws tag:
(These must be declared in the throws clause.)
(It is considered poor programming practice to include unchecked exceptions in the throws clause.)
Documenting these in the @throws tag is up to the judgment of the API designer, as described below.
Documenting Unchecked Exceptions
It is generally desirable to document the unchecked exceptions that a method can throw: this allows (but does not require) the caller to handle these exceptions. For example, it allows the caller to «translate» an implementation-dependent unchecked exception to some other exception that is more appropriate to the caller’s exported abstraction.
Since there is no way to guarantee that a call has documented all of the unchecked exceptions that it may throw, the programmer must not depend on the presumption that a method cannot throw any unchecked exceptions other than those that it is documented to throw. In other words, you should always assume that a method can throw unchecked exceptions that are undocumented.
Keep in mind that if you do not document an unchecked exception, other implementations are free to not throw that exception. Documenting exceptions properly is an important part of write-once, run-anywhere.
Background on Checked and Unchecked Exceptions
The idea behind checking an exception is that the compiler checks at compile-time that the exception is properly being caught in a try-catch block.
You can identify checked and unchecked exceptions as follows.
Note that whether an exception is checked or unchecked is not defined by whether it is included in a throws clause.
Background on the Throws Clause
Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check. For example (in java.lang.Class):
java.lang.Byte source code:
Note that the Java Language Specification also shows unchecked exceptions in throws clauses (as follows). Using the throws clause for unchecked exceptions in the spec is merely a device meant to indicate this exception is part of the contract between the caller and implementor. The following is an example of this (where «final» and «synchronization» are removed to make the comparison simpler).
java.util.Vector source code:
public Object elementAt(int index)
java.util.Vector spec in the Java Language Specification, 1st Ed. (p. 656):
Package-Level Comments
With Javadoc 1.2, package-level doc comments are available. Each package can have its own package-level doc comment source file that The Javadoc tool will merge into the documentation that it produces. This file is named package.html (and is same name for all packages). This file is kept in the source directory along with all the *.java files. (Do not put the packages.html file in the new doc-files source directory, because those files are only copied to the destination and are not processed.)
Here’s an example of a package-level source file for java.text and the file that the Javadoc tool generates:
(source file) javadoc (destination file)
The Javadoc tool processes package.html by doing three things:
How to Write Doc Comments for the Javadoc Tool
This document describes the style guide, tag and image conventions we use in documentation comments for Java programs written at Java Software, Oracle. It does not rehash related material covered elsewhere:
Contents
Introduction
Principles
At Java Software, we have several guidelines that might make our documentation comments different than those of third party developers. Our documentation comments define the official Java Platform API Specification. To this end, our target audience is those who write Java compatibility tests, or conform or re-implement the Java platform, in addition to developers. We spend time and effort focused on specifying boundary conditions, argument ranges and corner cases rather than defining common programming terms, writing conceptual overviews, and including examples for developers.
Writing API Specifications
The Java Platform API Specification is defined by the documentation comments in the source code and any documents marked as specifications reachable from those comments.
Notice that the specification does not need to be entirely contained in doc comments. In particular, specifications that are lengthy are sometimes best formatted in a separate file and linked to from a doc comment.
The Java Platform API Specification is a contract between callers and implementations.
The Specification describes all aspects of the behavior of each method on which a caller can rely. It does not describe implementation details, such as whether the method is native or synchronized. The specification should describe (textually) the thread-safety guarantees provided by a given object. In the absence of explicit indication to the contrary, all objects are assumed to be «thread-safe» (i.e., it is permissible for multiple threads to access them concurrently). It is recognized that current specifications don’t always live up to this ideal.
Unless otherwise noted, the Java API Specification assertions need to be implementation-independent. Exceptions must be set apart and prominently marked as such.
The Java API Specification should contain assertions sufficient to enable Software Quality Assurance to write complete Java Compatibility Kit (JCK) tests.
This means that the doc comments must satisfy the needs of the conformance testing by SQA. The comments should not document bugs or how an implementation that is currently out of spec happens to work.
Writing Programming Guide Documentation
It’s useful to go into further detail about how to document bugs and workarounds. There is sometimes a discrepancy between how code should work and how it actually works. This can take two different forms: API spec bugs and code bugs. It’s useful to decide up front whether you want to document these in the doc comments. At Java Software we have decided to document both of these outside of doc comments, though we do make exceptions.
API spec bugs are bugs that are present in the method declaration or in the doc comment that affects the syntax or semantics. An example of such a spec bug is a method that is specified to throw a NullPointerException when null is passed in, but null is actually a useful parameter that should be accepted (and was even implemented that way). If a decision is made to correct the API specification, it would be useful to state that either in the API specification itself, or in a list of changes to the spec, or both. Documenting an API difference like this in a doc comment, along with its workaround, alerts a developer to the change where they are most likely to see it. Note that an API specification with this correction would still maintain its implementation-independence.
Code bugs are bugs in the implementation rather than in the API specification. Code bugs and their workarounds are often likewise distributed separately in a bug report. However, if the Javadoc tool is being used to generate documentation for a particular implementation, it would be quite useful to include this information in the doc comments, suitably separated as a note or by a custom tag (say @bug ).
Who Owns and Edits the Doc Comments
The doc comments for the Java platform API specification is owned programmers. However, they are edited by both programmers and writers. It is a basic premise that writers and programmers honor each other’s capabilities and both contribute to the best doc comments possible. Often it is a matter of negotiation to determine who writes which parts of the documentation, based on knowledge, time, resources, interest, API complexity, and on the state of the implementation itself. But the final comments must be approved by the responsible engineer.
Ideally, the person designing the API would write the API specification in skeleton source files, with only declarations and doc comments, filling in the implementation only to satisfy the written API contract. The purpose of an API writer is to relieve the designer from some of this work. In this case, the API designer would write the initial doc comments using sparse language, and then the writer would review the comments, refine the content, and add tags.
If the doc comments are an API specification for re-implementors, and not simply a guide for developers, they should be written either by the programmer who designed and implemented the API, or by a API writer who is or has become a subject matter expert. If the implementation is written to spec but the doc comments are unfinished, a writer can complete the doc comments by inspecting the source code or writing programs that test the API. A writer might inspect or test for exceptions thrown, parameter boundary conditions, and for acceptance of null arguments. However, a much more difficult situation arises if the implementation is not written to spec. Then a writer can proceed to write an API specification only if they either know the intent of the designer (either through design meetings or through a separately-written design specification) or have ready access to the designer with their questions. Thus, it may be more difficult for a writer to write the documentation for interfaces and abstract classes that have no implementors.
With that in mind, these guidelines are intended to describe the finished documentation comments. They are intended as suggestions rather than requirements to be slavishly followed if they seem overly burdensome, or if creative alternatives can be found. When a complex system such as Java (which contains about 60 packages) is being developed, often a group of engineers contributing to a particular set of packages, such as javax.swing may develop guidelines that are different from other groups. This may be due to the differing requirements of those packages, or because of resource constraints.
Terminology
API documentation (API docs) or API specifications (API specs)
On-line or hardcopy descriptions of the API, intended primarily for programmers writing in Java. These can be generated using the Javadoc tool or created some other way. An API specification is a particular kind of API document, as described above. An example of an API specification is the on-line Java Platform, Standard Edition 7 API Specification.
Documentation comments (doc comments)
javadoc
The JDK tool that generates API documentation from documentation comments.
Source Files
The Javadoc tool can generate output originating from four different types of «source» files:
For more details, see: Source Files.
Writing Doc Comments
Format of a Doc Comment
Notes:
For more examples, see Simple Examples.
So lines won’t wrap, limit any doc-comment lines to 80 characters.
Here is what the previous example would look like after running the Javadoc tool:
getImage
Returns an Image object that can then be painted on the screen. The url argument must specify an absolute URL. The name argument is a specifier that is relative to the url argument.
This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.
Parameters:
Returns:
the image at the specified URL.
See Also:
Doc Comment Checking Tool
At Oracle, we have developed a tool for checking doc comments, called the Oracle Doc Check Doclet, or DocCheck. You run it on source code and it generates a report describing what style and tag errors the comments have, and recommends changes. We have tried to make its rules conform to the rules in this document.
DocCheck is a Javadoc doclet, or «plug-in», and so requires that the Javadoc tool be installed (as part of the Java 2 Standard Edition SDK).
Descriptions
First Sentence
The first sentence of each doc comment should be a summary sentence, containing a concise but complete description of the API item. This means the first sentence of each member, class, interface or package description. The Javadoc tool copies this first sentence to the appropriate member, class/interface or package summary. This makes it important to write crisp and informative initial sentences that can stand on their own.
This sentence ends at the first period that is followed by a blank, tab, or line terminator, or at the first tag (as defined below). For example, this first sentence ends at «Prof.»:
However, you can work around this by typing an HTML meta-character such as «&» or » java.lang.Runtime :
On Windows systems, the path search behavior of the loadLibrary method is identical to that of the Windows API’s LoadLibrary procedure.
The use of «On Windows» at the beginning of the sentence makes it clear up front that this is an implementation note.
Automatic re-use of method comments
You can avoid re-typing doc comments by being aware of how the Javadoc tool duplicates (inherits) comments for methods that override or implement other methods. This occurs in three cases:
A Style Guide
The following are useful tips and conventions for writing descriptions in doc comments.
Our audience is advanced (not novice) programmers, so it is generally not necessary to link to API in the java.lang package (such as String), or other API you feel would be well-known.
When referring to a method or constructor that has multiple forms, and you mean to refer to a specific form, use parentheses and argument types. For example, ArrayList has two add methods: add(Object) and add(int, Object):
The add(int, Object) method adds an item at a specified position in this arraylist.
However, if referring to both forms of the method, omit the parentheses altogether. It is misleading to include empty parentheses, because that would imply a particular form of the method. The intent here is to distinguish the general method from any of its particular forms. Include the word «method» to distinguish it as a method and not a field.
The add method enables you to insert items. (preferred)
The add() method enables you to insert items. (avoid when you mean «all forms» of the add method)
OK to use phrases instead of complete sentences, in the interests of brevity.
This holds especially in the initial summary and in @param tag descriptions.
The description is in 3rd person declarative rather than 2nd person imperative.
Gets the label. (preferred)
Get the label. (avoid)
A method implements an operation, so it usually starts with a verb phrase:
Gets the label of this button. (preferred)
This method gets the label of this button.
These API often describe things rather than actions or behaviors:
A button label. (preferred)
This field is a button label. (avoid)
For example, the description of the getToolkit method should read as follows:
Gets the toolkit for this component. (preferred)
Gets the toolkit for the component. (avoid)
The best API names are «self-documenting», meaning they tell you basically what the API does. If the doc comment merely repeats the API name in sentence form, it is not providing more information. For example, if method description uses only the words that appear in the method name, then it is adding nothing at all to what you could infer. The ideal comment goes beyond those words and should always reward you with some bit of information that was not immediately obvious from the API name.
Be aware that the word «field» has two meanings:
use «also known as» instead of «aka», use «that is» or «to be specific» instead of «i.e.», use «for example» instead of «e.g.», and use «in other words» or «namely» instead of «viz.»
Tag Conventions
This section covers:
Most of the following tags are specified in the Java Language Specification, First Edition. Also see the Javadoc reference page.
Order of Tags
Include tags in the following order:
Ordering Multiple Tags
We employ the following conventions when a tag appears more than once in a documentation comment. If desired, groups of tags, such as multiple @see tags, can be separated from the other tags by a blank line with a single asterisk.
Multiple @author tags should be listed in chronological order, with the creator of the class listed at the top.
Multiple @param tags should be listed in argument-declaration order. This makes it easier to visually match the list to the declaration.
Multiple @throws tags (also known as @exception) should be listed alphabetically by the exception names.
Multiple @see tags should be ordered as follows, which is roughly the same order as their arguments are searched for by javadoc, basically from nearest to farthest access, from least-qualified to fully-qualified, The following list shows this progression. Notice the methods and constructors are in «telescoping» order, which means the «no arg» form first, then the «1 arg» form, then the «2 arg» form, and so forth. Where a second sorting key is needed, they could be listed either alphabetically or grouped logically.
Required Tags
These principles expedite automated searches and automated processing. Frequently, too, the effort to avoid redundancy pays off in extra clarity.
Tag Comments
As a reminder, the fundamental use of these tags is described on the Javadoc Reference page. Java Software generally uses the following additional guidelines to create comments for each tag:
You can provide one @author tag, multiple @author tags, or no @author tags. In these days of the community process when development of new APIs is an open, joint effort, the JSR can be consider the author for new packages at the package level. For example, the new package java.nio has «@author JSR-51 Expert Group» at the package level. Then individual programmers can be assigned to @author at the class level. As this tag can only be applied at the overview, package and class level, the tag applies only to those who make significant contributions to the design or implementation, and so would not ordinarily include technical writers.
The @author tag is not critical, because it is not included when generating the API specification, and so it is seen only by those viewing the source code. (Version history can also be used for determining contributors for internal purposes.)
If the author is unknown, use «unascribed» as the argument to @author. Also see order of multiple @author tags.
The Java Software convention for the argument to the @version tag is the SCCS string «%I%, %G%», which converts to something like » 1.39, 02/28/97 » (mm/dd/yy) when the file is checked out of SCCS.
Parameter names are lowercase by convention. The data type starts with a lowercase letter to indicate an object rather than a class. The description begins with a lowercase letter if it is a phrase (contains no verb), or an uppercase letter if it is a sentence. End the phrase with a period only if another phrase or sentence follows it.
When writing the comments themselves, in general, start with a phrase and follow it with sentences if they are needed.
@param x the x-coordinate, measured in pixels
@param x the x-coordinate. Measured in pixels.
@param x Specifies the x-coordinate, measured in pixels.
@param x Specifies the x-coordinate. Measured in pixels.
Omit @return for methods that return void and for constructors; include it for all other methods, even if its content is entirely redundant with the method description. Having an explicit @return tag makes it easier for someone to find the return value quickly. Whenever possible, supply return values for special cases (such as specifying the value returned when an out-of-bounds argument is supplied).
Use the same capitalization and punctuation as you used in @param.
The @deprecated description in the first sentence should at least tell the user when the API was deprecated and what to use as a replacement. Only the first sentence will appear in the summary section and index. Subsequent sentences can also explain why it has been deprecated. When generating the description for a deprecated API, the Javadoc tool moves the @deprecated text ahead of the description, placing it in italics and preceding it with a bold warning: «Deprecated». An @see tag (for Javadoc 1.1) or <@link>tag (for Javadoc 1.2 or later) should be included that points to the replacement method:
If the member has no replacement, the argument to @deprecated should be «No replacement».
Do not add @deprecated tags without first checking with the appropriate engineer. Substantive modifications should likewise be checked first.
Specify the product version when the Java name was added to the API specification (if different from the implementation). For example, if a package, class, interface or member was added to the Java 2 Platform, Standard Edition, API Specification at version 1.2, use:
The Javadoc standard doclet displays a «Since» subheading with the string argument as its text. This subheading appears in the generated text only in the place corresponding to where the @since tag appears in the source doc comments (The Javadoc tool does not proliferate it down the hierarchy).
(The convention once was » @since JDK1.2 » but because this is a specification of the Java Platform, not particular to the Oracle JDK or SDK, we have dropped «JDK».)
When a package is introduced, specify an @since tag in its package description and each of its classes. (Adding @since tags to each class is technically not needed, but is our convention, as enables greater visibility in the source code.) In the absence of overriding tags, the value of the @since tag applies to each of the package’s classes and members.
When a class (or interface) is introduced, specify one @since tag in its class description and no @since tags in the members. Add an @since tag only to members added in a later version than the class. This minimizes the number of @since tags.
If a member changes from protected to public in a later release, the @since tag would not change, even though it is now usable by any caller, not just subclassers.
@throws (@exception was the original tag) (reference page)
See the Exceptions chapter of the Java Language Specification, Second Edition for more on exceptions. Also see order of multiple @throws tags.
@serial
@serialField
@serialData
(All added in Javadoc 1.2) (reference page)
For information about how to use these tags, along with an example, see «Documenting Serializable Fields and Data for a Class,» Section 1.6 of the Java Object Serialization Specification. Also see Oracle’s criteria for including classes in the serialized form specification.
(Added in Javadoc 1.2) (reference page)
Custom Tags and Annotations
If annotations are new to you, when you need to markup your source code, it might not be immediately clear whether to use an annotation or a Javadoc custom tag. Here is a quick comparison of the two.
In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.
If you need to affect both program semantics and documentation, you probably need both an annotation and a tag. For example, our guidelines now recommend using the @Deprecated annotation for alerting the compiler warning and the @deprecated tag for the comment text.
Documenting Default Constructors
Section 8.8.7 of the Java Language Specification, Second Edition describes a default constructor: If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided. It invokes the superclass constructor with no arguments. The constructor has the same access as its class.
Good programming practice dictates that code should never make use of default constructors in public APIs: All constructors should be explicit. That is, all default constructors in public and protected classes should be turned into explicit constructor declarations with the appropriate access modifier. This explicit declaration also gives you a place to write documentation comments.
The reason this is good programming practice is that an explicit declaration helps prevents a class from inadvertently being made instantiable, as the design engineer has to actually make a decision about the constructor’s access. We have had several cases where we did not want a public class to be instantiable, but the programmer overlooked the fact that its default constructor was public. If a class is inadvertently allowed to be instantiable in a released version of a product, upward compatibility dictates that the unintentional constructor be retained in future versions. Under these unfortunate circumstances, the constructor should be made explicit and deprecated (using @deprecated ).
Note that when creating an explicit constructor, it must match precisely the declaration of the automatically generated constructor; even if the constructor should logically be protected, it must be made public to match the declaration of the automatically generated constructor, for compatibility. An appropriate doc comment should then be provided. Often, the comment should be something as simple as:
Documenting Exceptions with @throws Tag
Documenting Exceptions in API Specs
Throws Tag
The purpose of the @throws tag is to indicate which exceptions the programmer must catch (for checked exceptions) or might want to catch (for unchecked exceptions).
Document the following exceptions with the @throws tag:
Documenting Unchecked Exceptions
It is generally desirable to document the unchecked exceptions that a method can throw: this allows (but does not require) the caller to handle these exceptions. For example, it allows the caller to «translate» an implementation-dependent unchecked exception to some other exception that is more appropriate to the caller’s exported abstraction.
Since there is no way to guarantee that a call has documented all of the unchecked exceptions that it may throw, the programmer must not depend on the presumption that a method cannot throw any unchecked exceptions other than those that it is documented to throw. In other words, you should always assume that a method can throw unchecked exceptions that are undocumented.
Keep in mind that if you do not document an unchecked exception, other implementations are free to not throw that exception. Documenting exceptions properly is an important part of write-once, run-anywhere.
Background on Checked and Unchecked Exceptions
The idea behind checking an exception is that the compiler checks at compile-time that the exception is properly being caught in a try-catch block.
You can identify checked and unchecked exceptions as follows.
Note that whether an exception is checked or unchecked is not defined by whether it is included in a throws clause.
Background on the Throws Clause
Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check. For example (in java.lang.Class):
java.lang.Byte source code:
Note that the Java Language Specification also shows unchecked exceptions in throws clauses (as follows). Using the throws clause for unchecked exceptions in the spec is merely a device meant to indicate this exception is part of the contract between the caller and implementor. The following is an example of this (where «final» and «synchronization» are removed to make the comparison simpler).
java.util.Vector source code:
public Object elementAt(int index)
java.util.Vector spec in the Java Language Specification, 1st Ed. (p. 656):
Package-Level Comments
With Javadoc 1.2, package-level doc comments are available. Each package can have its own package-level doc comment source file that The Javadoc tool will merge into the documentation that it produces. This file is named package.html (and is same name for all packages). This file is kept in the source directory along with all the *.java files. (Do not put the packages.html file in the new doc-files source directory, because those files are only copied to the destination and are not processed.)
The file package.html is an example of a package-level source file for java.text code> and package-summary.html is the file that the Javadoc tool generates.
The Javadoc tool processes package.html by doing three things:
How to write Java Doc
Posted by: Yatin in Core Java December 3rd, 2019 1 Comment Views
In this tutorial, we will learn how to write a Java Documentation (Java Doc or Javadoc) and the usage of JavaDoc tags.
1. Java Doc – Introduction
We can use any JavaDoc tool of their preference or the ALT + SHIFT + J key for generating a standard HTML documentation. In this tutorial, we will primarily focus on the keyboard keys but before going further let us take a deep dive at the Javadoc’s.
1.1 What is JavaDoc?
In software programming, JavaDoc is like multi-line comments but it contains some additional tags to prepare the HTML documentation of a class or a method.
1.2 JavaDoc Tags
The following table lists the commonly used JavaDoc tags.
Tags | Meaning | Used over? |
@see | Name of the associated class | Class, method |
@author | Author information such as name, email address, website, etc. | Class |
@version | Version information of a Class, Interface, or an Enum | Class |
@param | Constructor’s or Method’s input parameters information | Method |
@return | Information about the Return value of a method | Method |
@exception | Generated Exception in case of an invalid value | Method |
@throws | Generated Exception in case of an invalid value | Method |
@deprecated | Defines the element as deprecated/obsolete. Used by the compiler to generate the warnings | Class, Method |
@since | The API version in which this class, method, or a field was added | Class, Method |
To start with the captioned tutorial, we are hoping that users at present have their preferred Ide installed on their machines. For easy usage, I am using Eclipse Ide on a Windows operating system.
2. How to write Java Doc
We’ll demonstrate the use of commonly used JavaDoc tags in the software programming world. For a better understanding, developers can execute the below code in Eclipse Ide.
2.1 Example
Consider the following case that consists of two methods and their relevant JavaDoc.