558

I have a small code example I want to include in the Javadoc comment for a method.

/**
 * -- ex: looping through List of Map objects --
 * <code>
 * for (int i = 0; i < list.size(); i++) {
 *      Map map = (Map)list.get(i);
 *      System.out.println(map.get("wordID"));
 *      System.out.println(map.get("word"));
 * }
 * </code>
 * 
 * @param query - select statement
 * @return List of Map objects
 */

The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.

-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); } 
Parameters
query - - select statement 
Returns:
List of Map objects 

I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?

Michael Myers
  • 178,094
  • 41
  • 278
  • 290
Mark
  • 16,042
  • 9
  • 40
  • 55

17 Answers17

780

In addition to the already mentioned <pre> tags, you should also use the @code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:

* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>

Will give correct HTML output:

Set<String> s;
System.out.println(s);

While omitting the @code block (or using a <code> tag) will result in HTML like this:

Set s;
System.out.println(s);

(For reference, Java SE 8 tag descriptions can be found here: Javadoc Tags)

David Tonhofer
  • 12,954
  • 4
  • 44
  • 46
Fabian Steeg
  • 42,835
  • 6
  • 79
  • 111
  • 64
    I would have thought so too, but unfortunately it doesn't, you still need to add the
     tag to get line breaks.
    – Fabian Steeg Feb 12 '09 at 16:38
  • 12
    Unfortunately, it seems when you hit ctrl+shift+F (Format code in Eclipse), Eclipse messes up the {@code} tag and replaces it with {@code ... – jpdaigle May 13 '10 at 14:54
  • 3
    @jpdaigle I just tried this in Eclipse Galileo and Helios and the formatter does not replace anything for me (on Mac OS, but I have never seen the formatter do anything like that on other platforms either). – Fabian Steeg May 13 '10 at 22:40
  • 32
    Another unfortunate, if you have blocks in your example code using curly braces "{}", the first closing brace will terminate the @code block. One way around it is to use (wait for it...) html entities for the braces. I don't see a compelling argument for
     tags for code with blocks.
    – Ed Griebel Jan 27 '11 at 16:12
  • 2
    _Eclipse messes up the {@code} tag and replaces it with {@code-_ This isn't because of Eclipse, this is because of (bugged?) javadoc utility. If you have @ character in the multiline code inside {@code ...multiline...} then javadoc fails to parse it correctly:( At least this is what I see with Oracle JDK1.7.0_45 javadoc implementation. – Valentin Kovalenko Jan 03 '14 at 16:14
  • 2
    It also doesn't play well with @ symbols. – mkobit Oct 25 '14 at 04:17
  • 2
    I'm also having issues with using `@` symbol in code wrapped with `{@code}` tag. Without `{@code}` I can at least escape them with `{@literal @}` – jFrenetic Nov 17 '16 at 20:22
  • 2
    At last I stay with `
    {...}
    ` because I don't want to escape blocks with `{}`. `{@code ...}` eats that off.
    – WesternGun Feb 22 '18 at 17:17
  • If someone is looking here for kotlin android: https://stackoverflow.com/questions/40400593/kdoc-insert-code-snippet – Ultimo_m Mar 27 '18 at 10:03
  • Gradle 4.9 fails complaining about "unclosed inline {@code} tag" – badbishop Aug 02 '18 at 08:26
  • `
    {@code SomeCode}
    ` still works in Android Studio 3.6.1 (Java 8), unfortunately it ignores indented code like OP's `Map map = (Map)list.get(i);` (I tried spaces and tabs) and just uses the same indentation for everything.
    – Neph Apr 21 '20 at 14:34
175

I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:

  • usage of old <code> - tag to prevent the curly brackets from being interpreted
  • usage of "new" {@code ...} - tag to get the generics included in the output
  • escaping of the @ sign in @Override via "{@literal @}Override" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket
  • remove one space in front of {@code and {@literal, to compensate inner spaces and keep the alignment

javadoc code:

/** this methods adds a specific translator from one type to another type. `
  * i.e.
  * <pre>
  * <code>new BeanTranslator.Builder()
  *   .translate(
  *     new{@code Translator<String, Integer>}(String.class, Integer.class){
  *      {@literal @}Override
  *       public Integer translate(String instance) {
  *         return Integer.valueOf(instance);
  *       }})
  *   .build();
  * </code>
  * </pre>
  * @param translator
  */

gets printed as

new BeanTranslator.Builder()
  .translate(
    new Translator<String, Integer>(String.class, Integer.class){
      @Override
      public Integer translate(String instance) {
        return Integer.valueOf(instance);
      }})
  .build();
leventov
  • 12,780
  • 10
  • 60
  • 91
Christoph Naber
  • 1,751
  • 1
  • 10
  • 3
  • 2
    This works but I get a warning when running javadoc outputting this warning "warning: {@code} within " – Shane Rowatt Feb 24 '15 at 05:53
  • 4
    This is the one worked, the accepted answer don't work well in my eclipse (4.6.2). – user218867 May 17 '17 at 03:32
  • I wonder why all of this is necessary, my intellij 13 and later work fine with the code in the accepted answer. Is this just an eclipse issue ? – bvdb Jun 01 '18 at 09:46
  • Yes, I have also seen this work fine in IntelliJ 11 and later. IntelliJ handles it correctly. Unfortunately Eclipse does NOT render the JavaDoc correctly (hover state), and ignores both new lines and html breaks. I'm trying to find a solution that works well in both IDE's, since they are two of the top IDE's in use today. – Michael M Jun 05 '18 at 16:31
41

The java source has lots of good examples for this. Here's an example from the head of "String.java":

....
 * is equivalent to:
 * <p><blockquote><pre>
 *     char data[] = {'a', 'b', 'c'};
 *     String str = new String(data);
 * </pre></blockquote><p>
 * Here are some more examples of how strings can be used:
 * <p><blockquote><pre>
 *     System.out.println("abc");
 *     String cde = "cde";
 *     System.out.println("abc" + cde);
 *     String c = "abc".substring(2,3);
 *     String d = cde.substring(1, 2);
 * </pre></blockquote>
...
Steve B.
  • 49,740
  • 11
  • 90
  • 128
25

Enclose your multiline code with <pre></pre> tags.

Zach Scrivena
  • 27,585
  • 10
  • 60
  • 72
17

You need the <pre></pre> tags for the line breaks, and the {@code ... } inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic> tag, because then everything will be displayed on 1 line again.

Displays on one line:

* ..
* <pre>
* {@code
* public List<Object> getObjects() {
*    return objects;
* }
* </pre>
* ..

Displays with line breaks:

* ..
* <pre>
* {@code
* public List<Object> getObjects() 
* {
*    return objects;
* }
* </pre>
* ..

Another weird thing is when you paste the closing brace of {@code, it gets displayed:

* ..
* <pre>
* {@code
*   public List<Object> getObjects() 
*   {
*     return objects;
*   }
* }
* </pre>
* ..

Output:

public List<Object> getObjects() 
{
   return objects;
}
}
Paŭlo Ebermann
  • 68,531
  • 18
  • 138
  • 203
Rule
  • 573
  • 1
  • 7
  • 17
  • 4
    Welcome on Stack Overflow. To format code in posts, you can either prefix it (on a separate paragraph) by four spaces, or surround them by backticks (`` `...` ``). You don't need `` and `
    ` tags. I edited your answer in this mind.
    – Paŭlo Ebermann Aug 05 '11 at 03:24
10
/**
 * <blockquote><pre>
 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 * </pre></blockquote>
 **/
  • <pre/> is required for preserving lines.
  • {@code must has its own line
  • <blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}


UPDATE with JDK8

The minimum requirements for proper codes are <pre/> and {@code}.

/**
 * test.
 *
 * <pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre>
 */

yields

 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

And an optional surrounding <blockquote/> inserts an indentation.

/**
 * test.
 *
 * <blockquote><pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre></blockquote>
 */

yields

     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

Inserting <p> or surrounding with <p> and </p> yields warnings.

Jin Kwon
  • 17,188
  • 11
  • 87
  • 147
5

I was able to generate good looking HTML files with the following snip-it shown in Code 1.

 * <pre>
 * {@code
 * A-->B
 *  \
 *   C-->D
 *    \   \
 *     G   E-->F
 * }
 *</pre>

(Code 1)

Code 1 turned into the generated javadoc HTML page in Fig 1, as expected.

A-->B
 \
  C-->D
   \   \
    G   E-->F

(Fig. 1)

However, in NetBeans 7.2, if you hit Alt+Shift+F (to reformat the current file), Code 1 turns in to Code 2.

 * <
 * pre>
 * {@code
 * A-->B
 *  \
 *   C-->D
 *    \   \
 *     G   E-->F
 * }
 * </pre>

(Code 2)

where the first <pre> is now broken onto two lines. Code 2 produces generated javadoc HTML file as shown in Fig 2.

< pre> A-->B \ C-->D \ \ G E-->F

(Fig 2)

Steve B's suggestion (Code 3) seems to give the best results and remains formatted as expected even after hitting Alt+Shift+F.

*<p><blockquote><pre>         
* A-->B
*  \
*   C-->D
*    \   \
*     G   E-->F
* </pre></blockquote>

(Code 3)

Use of Code 3 produces the same javadoc HTML output as shown in Fig 1.

bitsdanceforme
  • 121
  • 2
  • 5
5

Here's my two cents.

As the other answers already state, you should use <pre> </pre> in conjuction with {@code }.

Use pre and {@code}

  • Wrapping your code inside <pre> and </pre> prevents your code from collapsing onto one line;
  • Wrapping your code inside {@code } prevents <, > and everything in between from disappearing. This is particularly useful when your code contains generics or lambda expressions.

Problems with annotations

Problems can arise when your code block contains an annotation. That is probably because when the @ sign appears at the beginning of the Javadoc line, it is considered a Javadoc tag like @param or @return. For example, this code could be parsed incorrectly:

/**
 * Example usage:
 *
 * <pre>{@code
 * @Override
 * public void someOverriddenMethod() {

Above code will disappear completely in my case.

To fix this, the line must not start with an @ sign:

/**
 * Example usage:
 *
 * <pre>{@code  @Override
 * public int someMethod() {
 *     return 13 + 37;
 * }
 * }</pre>
 */

Note that there are two spaces between @code and @Override, to keep things aligned with the next lines. In my case (using Apache Netbeans) it is rendered correctly.

MC Emperor
  • 17,266
  • 13
  • 70
  • 106
3

There is a significant difference between <blockquote><pre>... and <pre>{@code.... The former will omit the type declarations in generics but the latter will keep it.

E.g.: List<MyClass> myObject = null; displays as List myObject = null; with the firts and as List<MyClass> myObject = null; with the second

Tamas
  • 634
  • 1
  • 10
  • 24
2

If you are Android developer you can use:

<pre class=”prettyprint”>

TODO:your code.

</pre>

To pretty print your code in Javadoc with Java code.

ifeegoo
  • 6,262
  • 3
  • 26
  • 34
  • 1
    Please explain: what in Android's tools should make this work, considering the issues that require the @code tag? And which component should define the prettyprint class? Android uses regular Javadoc. – noamtm Feb 14 '17 at 06:53
  • Xamarin/VS, Android Studio, or does it not matter? – tyblu Jul 05 '17 at 18:14
  • @tyblu Android Studio works,but Xamarin Studio/VS maybe not work.You can have a try. – ifeegoo Jul 17 '17 at 02:07
1

I just read the Javadoc 1.5 reference here, and only the code with <and > must be enclosed inside {@code ...}. Here a simple example:

 /** 
 * Bla bla bla, for example:
 *
 * <pre>
 * void X() {
 *    List{@code <String>} a = ...;
 *    ...
 * }
 * </pre>
 *
 * @param ...
 * @return ...
 */
 .... your code then goes here ...
mljrg
  • 3,545
  • 1
  • 27
  • 42
1

Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.

Edwin
  • 2,603
  • 2
  • 18
  • 24
0

Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:

/**
 * <PRE>
 * insert code as you would anywhere else
 * </PRE>
 */

is the simplest way to do this.

An Example from a javadoc I got from a java.awt.Event method:

/**
 * <PRE>
 *    int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
 *    int offmask = CTRL_DOWN_MASK;
 *    if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
 *        ...
 *    }
 * </PRE>
 */

This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.

  • 2
    This doesn't add anything to the existing answers. – madth3 Oct 20 '12 at 00:18
  • madth3, you're right. I thought I had seen a difference when using lower vs. UPPERCASE pre modifiers, but on second look, it doesn't seem like it. It might also have something to do with how it appeared on this webpage vs. how it appears in javadoc. – Eugene_CD-adapco Nov 08 '12 at 23:43
  • 1
    case sensitive in the html tag? – Jasonw Dec 05 '12 at 07:37
0

In Visual Studio Code at least, you can force a Javadoc comment to respect line-breaks by wrapping it in triple-backticks, as seen below:

/** ```markdown
 * This content is rendered in (partial) markdown.
 * 
 * For example, *italic* and **bold** text works, but [links](https://www.google.com) do not.
 * Bonus: it keeps single line-breaks, as seen between this line and the previous.
 ``` */
Venryx
  • 8,962
  • 7
  • 50
  • 61
0

I work through these two ways without any problem:

<pre>
<code>
 ... java code, even including annotations
</code>
</pre>

and

<pre class="code">
 ... java code, even including annotations
</pre>

Of course the latter is more simplest and observe the class="code" part

Manuel Jordan
  • 11,959
  • 15
  • 69
  • 111
0

A combination of two of the other solutions seems perfect:

* <pre>{@code
*     {@literal @}Override
*     public void someMethod() {
*         Set<String> s;
*     }
* }</pre>

ie. use <pre>{@code to start and }</pre> to end the snippet. Also, replace @ with {@literal @}.

Haven't found an easier solution. Quite sad for a language that has been under active development for decades.

user1050755
  • 9,463
  • 3
  • 35
  • 51
0

I enclose my example code with <pre class="brush: java"></pre> tags and use SyntaxHighlighter for published javadocs. It doesn't hurt IDE and makes published code examples beautiful.

Jarek Przygódzki
  • 3,684
  • 2
  • 26
  • 39