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).
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.Mathutility 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 thejavadocCLI tool, mastering staticMathmethods (especially return types such asMath.pow()returningdouble), and generating random numbers within specified numeric ranges using bothMath.random()andjava.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 Style | Opening Delimiter | Closing Delimiter | Processed by javadoc Tool? | Typical Scope |
|---|---|---|---|---|
| Single-Line | // | End of physical line | No | Inline clarifications, temporary test edits |
| Multi-Line | /* | */ | No | Algorithm descriptions, multi-line code disabling |
| Javadoc | /** | */ | Yes | Public 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:
- Preceding Declarations Only: A Javadoc comment must appear immediately before the declaration of a class, interface, method, constructor, field, or package.
- 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. - Method Body Exclusion: Any
/** ... */comment placed inside a method body is treated by thejavadoctool 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@paramkeyword 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@returntag 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 avoidreturn type. Placing@returnon 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-authorflag is passed to thejavadocCLI.@version <version-text>: Documents the release version or build number of the artifact. Included in generated HTML only when the-versionflag is passed to thejavadocCLI.@see <reference>: Provides a cross-reference hyperlink to related classes, methods, or external URLs.
| Tag | Applicable Target | Syntax | Purpose & Exam Traps |
|---|---|---|---|
@param | Method, Constructor | @param name description | Documents input argument; name must match signature identifier. |
@return | Non-void Methods | @return description | Prohibited on constructors and void methods! |
@throws | Method, Constructor | @throws ExceptionType description | Documents potential exceptions; synonym for @exception. |
@author | Class, Interface | @author AuthorName | Documents author; included in HTML only when -author flag is passed. |
@version | Class, Interface | @version 1.0 | Documents version; included in HTML only when -version flag is passed. |
@see | All Declarations | @see Package#Member | Creates 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
- Cannot Be Instantiated: The
Mathclass is declaredpublic final class Mathand possesses aprivate Math() {}constructor. Any attempt to create an instance vianew Math()triggers a compile-time error. - Purely Static Members: Every method and constant in
Mathispublic static. They are invoked directly using the class name prefix:Math.methodName(). - Mathematical Constants:
Math.PI: $\approx 3.141592653589793$ (adoublevalue representing $\pi$).Math.E: $\approx 2.718281828459045$ (adoublevalue 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 adouble, even if both arguments passed to it are integers! Attempting to assign the result ofMath.pow()directly to anintvariable 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 along. - If passed a
float, it returns anint.
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 largestdoublevalue less than or equal toa(rounds down). Returns adouble.Math.ceil(a): Returns the smallestdoublevalue greater than or equal toa(rounds up). Returns adouble.
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:
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:
- Generating a random integer from
0to9inclusive:int val = (int) (Math.random() * 10); - Generating a random roll of a standard six-sided die (
1to6):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 to0. Then0 * 10evaluates to0. This expression ALWAYS evaluates to0!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,Randomis an instantiable class requiring thenewoperator:Random rand = new Random();. - Seed Support: Can be instantiated with a
longseed (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 signedintacross the full range ($-2^{31}$ to $2^{31}-1$).rand.nextInt(int bound): Returns a pseudo-randomintuniformly distributed between0(inclusive) andbound(exclusive): $0 \le \text{result} < \text{bound}$. Theboundargument must be strictly positive ($> 0$); passing $0$ or a negative value throwsjava.lang.IllegalArgumentException.- To simulate a die roll (1 to 6):
int die = rand.nextInt(6) + 1;
- To simulate a die roll (1 to 6):
rand.nextDouble(): Returns a pseudo-randomdoublein $[0.0, 1.0)$, identical in range toMath.random().rand.nextBoolean(): Returns a pseudo-randombooleanvalue (trueorfalse) with equal probability.
| Feature | java.lang.Math.random() | java.util.Random |
|---|---|---|
| Package | java.lang (no import needed) | java.util (explicit import required) |
| Invocation Style | Static method (Math.random()) | Instance methods on an instantiated object |
| Instantiation | Cannot instantiate (private constructor) | Must instantiate (new Random()) |
| Return Types | Returns double only | Overloaded: nextInt(), nextDouble(), nextBoolean(), nextLong() |
| Bounded Integers | Requires manual scaling and casting formula | Built-in method: rand.nextInt(int bound) |
| Seed Control | No seed control | Supports explicit seeds for test reproducibility |
A developer is writing Javadoc documentation for a class constructor. Which Javadoc tag is strictly NOT permitted within a constructor's documentation comment?
Consider the following code statement in a Java method:
What is the outcome when attempting to compile this statement?int power = Math.pow(2, 3);
A developer writes the following statement to generate an integer score from 0 to 9 inclusive:
What value will the variable score hold after this statement executes?int score = (int) Math.random() * 10;