Explain Codes LogoExplain Codes Logo

How can I use "<" and ">" in javadoc without formatting?

java
javadoc
html-escape-codes
javadoc-tags
Nikita BarsukovbyNikita Barsukov·Feb 11, 2025
TLDR

You can use HTML entities &lt; and &gt; to escape the angle brackets < and > in Javadoc.

Example:

/** * Sure this isn't a dating app, but we still get to compare: * Is {@code a &lt; b} or {@code a &gt; b}? * * @param a first int for consideration * @param b second int for selection * @return true if {@code a} is indeed less than {@code b} */ public boolean isLessThan(int a, int b) { return a < b; // No strings attached, just an innocent comparison }

Under the hood: why escaping is necessary

Direct usage of < and > in Javadoc is not recommended as these are HTML tag indicators. To prevent misinterpretations, we use the magic of HTML escape codes &lt; and &gt;. These codes help < and > to gallivant freely in your Javadoc comments - no misinterpretations, no harsh judgement.

Translating Javadoc speak: {@code} vs. {@literal}

When documenting generic text or non-code elements, {@literal ...} has got your back. On the other hand, {@code ...} is your best friend when you need to illustrate code snippets. For example:

/** * When you say "{@literal A&lt;B&gt;C}", no one bats an eye because we respect all data. * Conversely, when you say "{@code A&lt;B&gt;C}", everyone judges because we know that's not how code talks. */

Multiline code in Javadoc: The <pre>{@code}</pre> combo

For multilined code, mixing <pre> tags with {@code} is your ultimate winning move. The <pre> tag helps maintain the formatting, while {@code} ensures < and > can strut about incode style:

/** * A bit of deep code talks (it's not as scary as you think): * <pre>{@code * if (cats &lt; dogs) { * // Sorry cats, dogs are taking over the world! * } else if (cats &gt; dogs) { * // A world run by cats? Now that's a funny story. * } *}</pre> */

Deciding whether to use {@code} or {@literal}

  • Use {@code ...} when your Javadoc docs feature XML snippets or other pieces of code.
  • Embrace {@literal ...} when your text includes characters like <and >, or if you want these characters to play the hide and seek game in the Javadoc.

Potential pitfalls and solutions

  • Unescaped < and > may result in compilation errors and broken Javadoc layouts.
  • Older releases of the Javadoc tool may not recognize {@literal ...} and {@code ...} tags.
  • Always remember to check the official Java documentation for recent features and compatibility issues.