Documentation with
Comments
Learn how to write clear, professional documentation in Java using single-line comments, multi-line comments, and Javadoc to make your code readable, maintainable, and exam-ready.
What Are Comments?
Comments are human-readable annotations inserted into source code that the Java compiler completely ignores. They exist solely for programmers: to explain what code does, why a design choice was made, and how to use a class or method correctly.
Why Documentation Matters
Three Types of Java Comments
Single-Line Comments: //
Everything after // on the same line is ignored by the compiler. Use these for quick, targeted annotations directly next to the code they explain.
Multi-Line Comments: /* ... */
Multi-line comments begin with /* and end with */. Everything between those markers is ignored, even if it spans dozens of lines.
Javadoc Comments: /** ... */
Javadoc comments start with /** and use special tags like @param, @return, and @throws. The javadoc tool generates HTML documentation from them.
// vs /* */ vs /** */
| Feature | // Single | /* Multi */ | /** Javadoc */ |
|---|---|---|---|
| Scope | One line | Any span | Any span |
| Nestable? | N/A | No | No |
| Tags (@param) | No | No | Yes |
| Generates HTML | No | No | Yes |
| Best for | Quick notes | Block disabling | API docs |
Essential Javadoc Tags
Preconditions & Postconditions
How to Write Great Comments
Example 1: Simple Method
Example 2: Class-Level Javadoc
Example 3: Complex Method with Preconditions
Common Mistakes
Quick Reference Guide
| Situation | Comment Type | Example Tag/Style |
|---|---|---|
| Brief note on a line | // single-line | // handles edge case |
| Disable a code block | /* multi-line */ | /* ... old logic ... */ |
| Method documentation | /** Javadoc */ | @param, @return |
| Class documentation | /** Javadoc */ | @author |
| Contract specification | /** Javadoc */ | Precondition / Postcondition |
Question 1 of 5
Which comment syntax is specifically designed to generate HTML documentation in Java?
Question 2 of 5
A precondition in a method's documentation describes:
Question 3 of 5
Consider the following Javadoc comment:
/**
* Removes and returns the last element.
*
* @param list the list to modify
* @return the removed element
*/
The method signature is:
public static String removeLast(ArrayList<String> list)
Which of the following is missing from this documentation?
Question 4 of 5
Which of the following is an example of a poor comment?
Question 5 of 5
In Java, which of the following is true about multi-line comments?