9.2 Documentation with Javadoc & Core Utilities

Key Takeaways

  • Java supports three comment styles: single-line (//), multi-line (/* ... */), and Javadoc documentation comments (/** ... */), with only Javadoc comments parsed by the javadoc utility to generate external HTML documentation.
  • A Javadoc comment must immediately precede the declaration of a class, interface, method, constructor, or field; comments placed inside method bodies or detached from declarations are ignored by the javadoc tool.
  • The @return tag documents the return value of a method and is strictly prohibited on constructors and methods declared with a void return type.
  • The java.lang.Math class is final, cannot be instantiated, and provides static methods including Math.abs(), Math.max(), Math.min(), Math.sqrt(), Math.pow() (which always returns a double), and Math.round().
  • Math.random() generates a pseudo-random double in the range [0.0, 1.0) and requires parenthesized multiplication before integer casting, while java.util.Random must be instantiated and provides flexible generation through nextInt(int bound).
Last updated: September 2026

9.2 Documentation with Javadoc & Core Utilities

[!NOTE] Exam Focus: This section serves Oracle's "use the Math class" and "use the Random class" objectives alongside the commenting objectives from "Basic Java Elements". Candidates must demonstrate familiarity with Java's documentation mechanisms, the java.lang.Math utility class, and random number generation. Key objectives include distinguishing between comment styles, recognizing correct Javadoc tag syntax (@param, @return, @author, @version, @throws), identifying valid comment placement, understanding the javadoc CLI tool, mastering static Math methods (especially return types such as Math.pow() returning double), and generating random numbers within specified numeric ranges using both Math.random() and java.util.Random.

Software development is an intrinsically collaborative engineering discipline. Code is read far more frequently than it is written. To ensure software maintainability and API discoverability, Java provides a standardized, language-integrated documentation mechanism known as Javadoc. Furthermore, Java equips developers with core mathematical utilities in java.lang.Math and random number generators in java.util.Random. Mastering both documentation and core utility classes is essential for the 1Z0-811 certification.


1. Java Comment Taxonomy

The Java programming language supports three distinct types of comments. The Java compiler ignores all comments during tokenization and parsing, meaning comments contribute zero bytes to compiled .class files and incur zero runtime performance penalty.

// 1. Single-Line Comment: Extends from the double slashes to the end of the line

/* 2. Multi-Line (Block) Comment:
      Spans across multiple lines
      until the closing delimiter is reached */

/**
 * 3. Javadoc Documentation Comment:
 *    Special block comment recognized by the javadoc utility.
 */

A. Single-Line Comments (//)

A single-line comment begins with two consecutive forward slashes (//). The compiler discards all characters starting from // up to the end of that physical line. Single-line comments are typically used for brief, inline explanations of complex statements or for temporarily commenting out a single line of code during debugging.

B. Multi-Line (Traditional) Comments (/* ... */)

A multi-line (or block) comment begins with /* and terminates with */. Everything between these two delimiter sequences is ignored by the compiler. Block comments are ideal for documenting longer algorithm descriptions or temporarily disabling blocks of code spanning several lines.

[!WARNING] Nesting Trap: In Java, multi-line comments cannot be nested. If you place /* inside an existing block comment, the compiler does not treat it as an inner comment. The very first */ encountered will terminate the entire block comment, causing any subsequent text or closing */ markers to trigger a compile-time syntax error.

C. Javadoc Documentation Comments (/** ... */)

A Javadoc documentation comment begins with a forward slash followed immediately by two asterisks (/**) and terminates with a single asterisk and forward slash (*/). While the standard javac compiler treats Javadoc comments as regular whitespace, the specialized javadoc tool parses their internal contents to construct HTML API documentation.

Comment StyleOpening DelimiterClosing DelimiterProcessed by javadoc Tool?Typical Scope
Single-Line//End of physical lineNoInline clarifications, temporary test edits
Multi-Line/**/NoAlgorithm descriptions, multi-line code disabling
Javadoc/***/YesPublic APIs: classes, interfaces, methods, fields

2. Javadoc Comment Placement Rules & Standard Tags

For the javadoc tool to link a documentation comment to a specific program element, the comment must adhere to strict structural placement rules:

  1. Preceding Declarations Only: A Javadoc comment must appear immediately before the declaration of a class, interface, method, constructor, field, or package.
  2. No Intervening Code: No executable statements or variable declarations may intervene between the closing delimiter */ and the element's declaration header. If a statement is placed between the comment and the declaration, the Javadoc comment is orphaned and ignored.
  3. Method Body Exclusion: Any /** ... */ comment placed inside a method body is treated by the javadoc tool as a standard non-documentation comment and is completely omitted from the generated HTML documentation.
/**
 * Represents a bank account in the retail banking system.
 * 
 * @author Finance Engineering Team
 * @version 2.4
 */
public class BankAccount {

    /** The unique ten-digit account identifier. */
    private String accountNumber;

    /**
     * Debits the specified monetary amount from the account balance.
     * 
     * @param amount the non-negative monetary sum to withdraw
     * @return true if withdrawal succeeded; false if balance was insufficient
     * @throws IllegalArgumentException if amount is negative
     */
    public boolean withdraw(double amount) {
        /** INSIDE a method body: javadoc WILL IGNORE THIS COMMENT! */
        if (amount < 0) {
            throw new IllegalArgumentException("Amount cannot be negative.");
        }
        return true;
    }
}

Standard Javadoc Tags

Javadoc comments employ structured metadata annotations called tags. All Javadoc tags begin with the @ symbol, must be lowercase, and are placed at the beginning of a line (following the leading asterisk).

  • @param <parameter-name> <description>: Documents a method or constructor parameter. The @param keyword must be followed by the exact name of the parameter identifier, followed by an explanation of the parameter's purpose or constraints.
  • @return <description>: Documents the return value of a method.

[!IMPORTANT] Critical Exam Rule on @return: The @return tag is permitted only on methods that declare a non-void return type! It must never be used on constructors (which have no return type) or methods declared with a void return type. Placing @return on a constructor or void method is a classic exam trap.

  • @throws <exception-class> <description> (or @exception): Documents any checked or unchecked exceptions that a method or constructor might throw during execution.
  • @author <name>: Documents the author or team responsible for the class or interface. Included in generated HTML only when the -author flag is passed to the javadoc CLI.
  • @version <version-text>: Documents the release version or build number of the artifact. Included in generated HTML only when the -version flag is passed to the javadoc CLI.
  • @see <reference>: Provides a cross-reference hyperlink to related classes, methods, or external URLs.
TagApplicable TargetSyntaxPurpose & Exam Traps
@paramMethod, Constructor@param name descriptionDocuments input argument; name must match signature identifier.
@returnNon-void Methods@return descriptionProhibited on constructors and void methods!
@throwsMethod, Constructor@throws ExceptionType descriptionDocuments potential exceptions; synonym for @exception.
@authorClass, Interface@author AuthorNameDocuments author; included in HTML only when -author flag is passed.
@versionClass, Interface@version 1.0Documents version; included in HTML only when -version flag is passed.
@seeAll Declarations@see Package#MemberCreates hyperlink to related class, method, or URL.

3. The javadoc Command-Line Tool and Self-Documenting Code

The JDK includes a command-line tool named javadoc (located in the bin/ directory alongside javac and java). The javadoc utility parses Java source files, extracts class declarations and /** ... */ comments, and produces a complete static website containing interconnected HTML documentation.

Command-Line Syntax and the -d Flag

javadoc -d docs src/com/oracle/payroll/*.java

The -d (destination) option specifies the target directory where javadoc will save the generated HTML files, cascading style sheets (stylesheet.css), and JavaScript search indices. If the specified directory does not exist, javadoc automatically creates it. If the -d option is omitted, javadoc outputs all HTML files into the current working directory, resulting in severe filesystem clutter.

Key generated artifacts include index.html (the entry portal), package-summary.html (package contents), ClassName.html (detailed class APIs), and overview-tree.html (inheritance tree).

Principles of Self-Documenting Code

Modern software engineering emphasizes self-documenting code (intention-revealing code). Clear identifier names eliminate the need for cluttering comments:

// Bad: Cryptic variable names requiring an explanatory comment
double d = p * r * t; // Calculate simple interest using principal, rate, time

// Good: Self-documenting code requiring zero comments
double simpleInterest = principalAmount * annualInterestRate * loanDurationYears;

Comments should be reserved to explain the "why" (business rules, non-obvious design rationales, regulatory constraints), not merely restating the "what".


4. The java.lang.Math Utility Class

The java.lang.Math class provides static methods and constants for elementary mathematical computations. It is part of the java.lang package, meaning it is automatically imported into every Java source file without requiring an explicit import statement.

Architectural Characteristics of Math

  1. Cannot Be Instantiated: The Math class is declared public final class Math and possesses a private Math() {} constructor. Any attempt to create an instance via new Math() triggers a compile-time error.
  2. Purely Static Members: Every method and constant in Math is public static. They are invoked directly using the class name prefix: Math.methodName().
  3. Mathematical Constants:
    • Math.PI: $\approx 3.141592653589793$ (a double value representing $\pi$).
    • Math.E: $\approx 2.718281828459045$ (a double value representing the base of natural logarithms).

Core Math Methods Tested on 1Z0-811

Math.abs(x)

Returns the absolute (non-negative) value of an argument. Overloaded for int, long, float, and double:

Math.abs(-25);    // returns int: 25
Math.abs(-14.8);  // returns double: 14.8

Math.max(a, b) and Math.min(a, b)

Returns the greater or lesser of two values. Overloaded for int, long, float, and double:

Math.max(12, 19);     // returns int: 19
Math.min(3.14, 2.71); // returns double: 2.71

Math.sqrt(double a)

Returns the positive square root of a double value. If the argument is negative, it returns Double.NaN (Not-a-Number):

Math.sqrt(25.0); // returns double: 5.0
Math.sqrt(-4.0); // returns double: NaN

Math.pow(double base, double exp)

Returns the value of the first argument raised to the power of the second argument ($base^{exp}$).

[!IMPORTANT] The Math.pow() Return Type Trap: Math.pow() always returns a double, even if both arguments passed to it are integers! Attempting to assign the result of Math.pow() directly to an int variable without an explicit cast causes a compile-time lossy conversion error:

int result = Math.pow(2, 3); // COMPILE ERROR: possible lossy conversion from double to int
int correct = (int) Math.pow(2, 3); // Valid: explicitly cast 8.0 to int 8

Math.round(x)

Returns the closest whole number to the argument. Halfway values round up toward positive infinity:

  • If passed a double, it returns a long.
  • If passed a float, it returns an int.
Math.round(5.4);  // returns long: 5
Math.round(5.5);  // returns long: 6
Math.round(-5.5); // returns long: -5 (rounds toward positive infinity!)

Math.floor(double a) and Math.ceil(double a)

  • Math.floor(a): Returns the largest double value less than or equal to a (rounds down). Returns a double.
  • Math.ceil(a): Returns the smallest double value greater than or equal to a (rounds up). Returns a double.
Math.floor(4.9);  // returns double: 4.0
Math.ceil(4.1);   // returns double: 5.0

5. Pseudo-Random Number Generation: Math.random() vs. java.util.Random

Java provides two complementary approaches for generating pseudo-random values: the static convenience method Math.random() and the dedicated utility class java.util.Random.

A. Math.random()

The Math.random() static method returns a pseudo-random double value uniformly distributed in the half-open range:

0.0Math.random()<1.00.0 \le \text{Math.random()} < 1.0

Crucially, Math.random() can return 0.0, but it never returns 1.0.

Scaling Math.random() to an Integer Range

To generate an integer in the range from min to max inclusive, apply the standard scaling formula:

int randomNumber=(int)(Math.random()×(maxmin+1))+min;\text{int randomNumber} = (\text{int}) (\text{Math.random()} \times (\text{max} - \text{min} + 1)) + \text{min};

  • Generating a random integer from 0 to 9 inclusive: int val = (int) (Math.random() * 10);
  • Generating a random roll of a standard six-sided die (1 to 6): int diceRoll = (int) (Math.random() * 6) + 1;

The Precedence Casting Trap

[!CAUTION] Classic 1Z0-811 Exam Trap: The cast operator (int) has higher operator precedence than the multiplication operator *. Look at the difference between these two statements:

// WRONG: (int) binds directly to Math.random() first!
int flawed = (int) Math.random() * 10;

Because Math.random() returns a double in $[0.0, 1.0)$, casting it to (int) truncates the decimal portion to 0. Then 0 * 10 evaluates to 0. This expression ALWAYS evaluates to 0!

To fix this, parentheses must enclose the multiplication before casting:

// CORRECT: Multiplication occurs before casting
int correct = (int) (Math.random() * 10);

B. The java.util.Random Class

While Math.random() is convenient for quick one-off values, java.util.Random is a full-featured class that provides flexible generators for diverse data types.

Characteristics of java.util.Random

  • Requires Import: Must be imported via import java.util.Random;.
  • Must Be Instantiated: Unlike Math, Random is an instantiable class requiring the new operator: Random rand = new Random();.
  • Seed Support: Can be instantiated with a long seed (new Random(42L)). Two generators initialized with identical seeds produce identical pseudo-random sequences, which is invaluable for deterministic testing.

Core Random Methods

  • rand.nextInt(): Returns a pseudo-random 32-bit signed int across the full range ($-2^{31}$ to $2^{31}-1$).
  • rand.nextInt(int bound): Returns a pseudo-random int uniformly distributed between 0 (inclusive) and bound (exclusive): $0 \le \text{result} < \text{bound}$. The bound argument must be strictly positive ($> 0$); passing $0$ or a negative value throws java.lang.IllegalArgumentException.
    • To simulate a die roll (1 to 6): int die = rand.nextInt(6) + 1;
  • rand.nextDouble(): Returns a pseudo-random double in $[0.0, 1.0)$, identical in range to Math.random().
  • rand.nextBoolean(): Returns a pseudo-random boolean value (true or false) with equal probability.
Featurejava.lang.Math.random()java.util.Random
Packagejava.lang (no import needed)java.util (explicit import required)
Invocation StyleStatic method (Math.random())Instance methods on an instantiated object
InstantiationCannot instantiate (private constructor)Must instantiate (new Random())
Return TypesReturns double onlyOverloaded: nextInt(), nextDouble(), nextBoolean(), nextLong()
Bounded IntegersRequires manual scaling and casting formulaBuilt-in method: rand.nextInt(int bound)
Seed ControlNo seed controlSupports explicit seeds for test reproducibility
Loading diagram...
Javadoc Processing and Math/Random Utility Architecture
Test Your Knowledge

A developer is writing Javadoc documentation for a class constructor. Which Javadoc tag is strictly NOT permitted within a constructor's documentation comment?

A
B
C
D
Test Your Knowledge

Consider the following code statement in a Java method:

int power = Math.pow(2, 3);
What is the outcome when attempting to compile this statement?

A
B
C
D
Test Your Knowledge

A developer writes the following statement to generate an integer score from 0 to 9 inclusive:

int score = (int) Math.random() * 10;
What value will the variable score hold after this statement executes?

A
B
C
D