Skip to Content
97 Things Every Java Programmer Should Know
book

97 Things Every Java Programmer Should Know

by Kevlin Henney, Trisha Gee
May 2020
Beginner
267 pages
7h 37m
English
O'Reilly Media, Inc.
Content preview from 97 Things Every Java Programmer Should Know

Chapter 46. Kinds of Comments

Nicolai Parlog

Assume you want to put some comments into your Java code. Do you use /**, /*, or //? And where exactly do you put them? Beyond syntax, there are established practices that attach semantics to which is used where.

Javadoc Comments for Contracts

Javadoc comments (the ones enclosed in /** ...​ */) are exclusively used on classes, interfaces, fields, and methods and are placed directly above them. Here is an example from Map::size:

/**
 * Returns the number of key-value mappings in this map. If the
 * map contains more than Integer.MAX_VALUE elements, returns
 * Integer.MAX_VALUE.
 *
 * @return the number of key-value mappings in this map
 */
int size();

The example demonstrates syntax as well as semantics: a Javadoc comment is a contract. It promises API users what they can expect while keeping the type’s central abstraction intact by not talking about implementation details. At the same time, it binds implementers to provide the specified behavior.

Java 8 relaxed this strictness a little while formalizing different interpretations by introducing the (nonstandardized) tags @apiNote, @implSpec, and @implNote.  The prefixes, api or impl, specify whether the comment addresses users or implementers. The suffixes, Spec or Note, clarify whether this is actually a specification or only for illustration. Notice how @apiSpec is missing? That’s because ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

97 Things Every Programmer Should Know

97 Things Every Programmer Should Know

Kevlin Henney
Java Coding Problems

Java Coding Problems

Anghel Leonard
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781491952689Errata Page