DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • How to Convert HTML to DOCX in Java

Trending

  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Segmentation Violation and How Rust Helps Overcome It
  • Chaos Engineering for Microservices
  1. DZone
  2. Coding
  3. Java
  4. A Guide to Formatting Code Snippets in Javadoc

A Guide to Formatting Code Snippets in Javadoc

Brush up on your Javadoc formatting skills with this guide to using the pre, code , and {@code} tags—and deciding when to use each of them

By 
Tom Hombergs user avatar
Tom Hombergs
·
Updated Aug. 25, 17 · Tutorial
Likes (17)
Comment
Save
Tweet
Share
32.0K Views

Join the DZone community and get the full member experience.

Join For Free

Sometimes we want to add code snippets to our Javadoc comments, especially when developing an API of some kind. But how do you mark the code snippet so that it will be rendered correctly in the final Javadoc HTML, especially when special characters like <, > and @ are involved?

Since there are multiple options to do this — each with different results — this blog post gives an overview of these options and a guideline on when to use which.

<pre>, <code>, {@code}, what?

Javadoc supports three different features for code markup. These are the HTML tags <pre> and <code> and the Javadoc tag  {@code} . Sounds great, but each time I want to include a code snippet in a Javadoc comment, I'm wondering which of the three to use and what the difference between them actually is.

To assemble a definitive guide on when to use which of the markup features, I took a look at how they behave by answering the following questions for each of them:

Question

Rationale

Are indentations and line breaks displayed correctly in the rendered Javadoc?

For multi-line code snippets indentations and line breaks are essential, so they must not get lost when rendering the Javadoc.

Are  <  and  >  displayed correctly in the rendered Javadoc?

 <  and  >  should not be evaluated as part of an HTML tag but instead be displayed literally. This is especially important for code snippets containing HTML or XML code or Java code containing generics.

Is  @  displayed correctly in the rendered Javadoc?

 @  should not be evaluated as part of a Javadoc tag but instead be displayed literally. This is important for Java code containing annotations.

Can special characters like the ones above be escaped using HTML number codes like&#60;,&#62; and &#64; (which evaluate to  < , >   and  @ )?

If the special characters **cannot be displayed literally**, they should at least be escapable via HTML codes.

<pre>

<pre> is the default HTML tag for preformatted text. This means that HTML renderers by default know that the code within the tag should be displayed literally. Thus, line breaks and indentation are supported. However, since we're in a Javadoc environment, @ is evaluated as a Javadoc tag, and since we're also in an HTML environment, < and > are evaluated as HTML tags. So none of these characters will be displayed correctly in the rendered Javadoc HTML, so they have to be escaped.

So ...

/**
 * <pre>
 * public class JavadocTest {
 *   // indentation and line breaks are kept 
 * 
 *   &#64;SuppressWarnings
 *   public List&#60;String&#62; generics(){
 *     // '@', '<' and '>'  have to be escaped with HTML codes
 *     // when used in annotations or generics
 *   }
 * } 
 * </pre>
 */
public class PreTest {}


... renders to ...

public class JavadocTest {
   // indentation and line breaks are kept 

   @SuppressWarnings
   public List<String> generics(){
     // '@', '<' and '>'  have to be escaped with HTML codes
     // when used in annotations or generics
   }
 } 


<code>

Within a <code> tag, not even the indentation and line breaks are kept and our special characters still have to be escaped.

And so ....

/**
 * Using &#60;code&#62;, indentation and line breaks are lost. 
 * '@', '<' and '>'  have to be escaped with HTML codes.
 * 
 * An annotation <code>&#64;Foo</code>; and a generic List&#60;String&#62;.
 */
public class CodeHtmlTagTest {}


... renders to ...

Using <code>, indentation and line breaks are lost. '@', '<' and '>' have to be escaped with HTML codes. An annotation @Foo; and a generic List<String>.


{@code}

{@code} is a Javadoc tag that came with Java 5. A code snippet embedded within {@code} will display our special characters correctly so they don't need to be manually escaped. However, indentation and line breaks will be lost. This can be rectified by using {@code} together with <pre>, though (see the next section).

/**
 * Using {@code @code} alone, indentation will be lost, but you don't have to
 * escape special characters:
 * 
 * {@code An annotation <code>@Foo</code>; and a generic List<String>}.
 */
public class CodeJavadocTagTest {}


Renders to ...

Using @code alone, indentation will be lost, but you don't have to escape special characters: An annotation <code>@Foo</code>; and a generic List<String>.


<pre> + {@code}

Combining <pre> and {@code}, indentations and line breaks are kept and < and > don't have to be escaped. However, the  @ character is now evaluated as a Javadoc tag if it is followed with a non-whitespace character. What's worse: it cannot even be escaped using the HTML number code, since the HTML number code would be literalized by {@code}.

/**
 * <pre>{@code 
 * public class JavadocTest {
 *   // indentation and line breaks are kept 
 * 
 *  @literal @SuppressWarnings
 *   public List<String> generics(){
 *     // '<' and '>'  are displayed correctly
 *     // '@' CANNOT be escaped with HTML code, though!
 *   }
 * } 
 * }</pre>
 */
public class PreTest {}


Renders to ...

public class JavadocTest {
    // indentation and line breaks are kept 

    &#64;SuppressWarnings
    public List<String> generics(){
        // '<' and '>'  are displayed correctly
        // '@' CANNOT be escaped with HTML code, though!
    }
}


Note that you actually can escape an @ using  @literal @  within the the  {@code}  block. However, this option always renders an unwanted whitespace before the @ character, which is why I don't discuss that option any further.

Summary

The following table summarizes the different Javadoc code markup features.

<pre>...</pre> <code>...</code> {@code ...} <pre>{@code ...}</pre>
keep indentation & line breaks yes no no yes
display '<' and '>' correctly no no yes yes
display '@' correctly no no yes no
escape special characters via HTML number codes yes yes no need to escape no

When to Use Which?

Looking at the table above, sadly, there is no single best option. Which option to use depends on the content of the code snippet you want to embed in your Javadoc. The following guidelines can be derived for different situations:

Situation Code Markup Feature Rationale
inline code snippet {@code ...} With {@code...} you don't need to escape special characters. For inline snippets, it doesn't matter that line breaks are lost
multi-line Java code snippet <pre>...</pre> For multi-line snippets, you need line breaks. So only <pre> and the combination of <pre>and {@code...}. However, only <pre> allows the use of '@' (escaped using HTML number codes), which you need for Java code containing annotations.
mutli-line HTML / XML code snippet <pre>{@code...}</pre> In HTML or XML code you probably need a lot of '<' and '>' while '@' is not as important, so it doesn't matter that '@' cannot be displayed. If you need an '@', you have to fall back on <pre>
code style Javadoc Snippet (programming) HTML

Published at DZone with permission of Tom Hombergs. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript
  • How to Convert HTML to DOCX in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!