Explain Codes LogoExplain Codes Logo

Good example of Javadoc

java
javadoc
best-practices
java-8
Nikita BarsukovbyNikita Barsukov·Feb 8, 2025
TLDR
/** * Calculates the product of two non-negative integers faster than a * caffeinated coder crunching numbers. ☕ * * @param x First multiplicand. Don't send negatives here, they're not invited. * @param y Second multiplicand. Also dislikes negatives. * @return Product of x and y. Multiplication magic! * @throws IllegalArgumentException if either x or y is negative. Remember, no negatives! */ public int multiply(int x, int y) { if (x < 0 || y < 0) { throw new IllegalArgumentException("Both x and y must be >= 0. We don't like negativity around here!"); } return x * y; }

Stand out in your Javadoc: Describe parameters, don't skimp on validation, and be brave with exception conditions. Your readers will thank you!

Creating tailor-made Javadoc: a step-by-step guide

Let's jump in to crafting examples of on-point, easy-to-follow Javadocs:

Write it like you mean it: Use active voice

Active voice gives clear direction. For example:

  • "Returns the size" vs "The size is returned".
  • "Throws IOException" rather than "IOException is thrown".

Is it safe? Say it loud! (Thread safety)

Provide robots and humanfolk with danger-level intel. Use terms like "thread-safe" or "not thread-safe".

/** * Thread-safe counter that even race conditions are afraid of. */ public class ThreadSafeCounter { // Implementation details... }

Handle depreciation with grace

Why it's deprecated, what to use instead, and how to move existing code, all in a neat little package. Because everyone deserves to know.

/** * @deprecated Feelin' old since version 3.2. Instead, hangout with {@link NewFeature}, the cool kid on the block. Trust us, it's faster, sleeker, and wouldn't steal your lunch money. */ @Deprecated public class OldFeature { // Implementation details... }

Javadoc: the recipe for success

Here are some pro-tips. Let's see what the masters have to say:

The Art of Simplicity

Check out the JDK's Collections class. Brevity and precision go hand in hand. Save the reader’s time and they'll love you forever.

Show, don’t tell - provide usage examples

Seeing is believing. Check out Apache Commons Lang for neat and practical examples.

/** * Capitalizes a String changing the first letter to a title case. * * <pre> * StringUtils.capitalize(null) = null * StringUtils.capitalize("") = "" // Because "" shouts "nothing", louder. * StringUtils.capitalize("cat") = "Cat" // "Meow" just became "MEOW"! * StringUtils.capitalize("cAt") = "CAt" * </pre> * * @param str the String to capitalize, may be null * @return the capitalized String, {@code null} if null String input */ public static String capitalize(String str) { // Implement... }

Use the {@link ClassName#methodName} to help your readers hit the road exploring related components. Especially handy for larger libraries.