For proper handling of HTML entities like '<' and '>' especially in generics, {@code} can be a lifesaver:
/**
* An example showcasing generics:
* <pre>{@code * public static <T> void arrayPrinter(T[] items) {
* for (T item : items) {
* System.out.println(item); // Prints, not shouts!
* }
* }
* }</pre>
*/
Displaying the @ sign
To showcase the @ sign in your Javadoc code, use {@literal @} for accurate rendering:
/**
* Example showing how to use @ in Javadoc:
* <pre>{@code * String email = "example{@literal @}email.com"; // No, it's not my real email!
* }</pre>
*/
Improving readability and organizing
For better readability and organization, use HTML lists and line breaks in your Javadoc content:
/**
* Showcasing multiple points with details:
* <pre>{@code * yourMethod(); // Spoiler: This method is epic!
* }</pre>
* <ul>
* <li>A crucial point about the method</li>
* <li>A second major detail</li>
* <li>Yet another key facet</li>
* </ul>
* <br/>
* Practical Instance:
* <pre>{@code * anotherMethod(); // Yes, another method. Hold your applause.
* }</pre>
*/
Code examples with explanations
A great Javadoc not only shows, but tells. Include explanations with your code examples for clarity:
/**
* Demystifying thread synchronization:
* <pre>{@code * synchronized (object) {
* // The treasure room: only one thread allowed at a time.
* }
* }</pre>
* This keeps your shared resource (the treasure) safe from concurrency issues (the treasure hunters)!
*/
Pitfalls and how to avoid them
Formatting issues can crop up when {@code} escapes us. This is prominently seen with angle brackets in Generics:
// Incorrect usage without {@code}, angle brackets get parsed as HTML:/**
* <pre>
* List<String> stringList = new ArrayList<>();
* </pre>
*/// Correct usage with {@code}, enclosed within <pre> tags:/**
* <pre>{@code * List<String> stringList = new ArrayList<>(); // An empty list, like my weekend party schedule!
* }</pre>
*/
Following real-world examples
Real-world examples, like the String class in Java SE, are ideal for understanding Javadoc structure and formatting:
/**
* Sample inspired by the 'String' Java SE documentation:
* <pre>{@code * String str = "foo";
* char ch = str.charAt(0); // Spoiler: It's 'f'.
* }</pre>
* charAt(int index) is the magic wand that reveals the character hiding at the specified index.
*/