Comments in Java – Single-line, Multi-line and Javadoc
Comments are notes in your source code that the compiler ignores. They explain why code exists, warn about tricky parts, and, in the case of Javadoc comments, become the official documentation of your classes and methods.
Java has three kinds of comments: single-line, multi-line and documentation (Javadoc) comments. This tutorial shows each one, the most useful Javadoc tags, how to generate HTML documentation, and how to write comments that actually help.
1. The Three Types of Comments
| Type | Syntax | Used for |
|---|---|---|
| Single-line | // text | Short notes, end-of-line remarks, temporarily disabling a line |
| Multi-line (block) | /* text */ | Longer explanations inside code |
| Documentation (Javadoc) | /** text */ | Describing classes, methods and fields for API documentation |
/**
* Demonstrates the three kinds of comments in Java.
*/
public class CommentTypes {
public static void main(String[] args) {
// Single-line comment: everything after // is ignored
int width = 8; // comments can also follow code on the same line
/*
* Multi-line comment: useful for longer explanations
* that span several lines.
*/
int height = 5;
int area = width * height /* inline block comment */ ;
System.out.println("Area: " + area);
// System.out.println("This line is commented out and will not run");
}
}
Area: 40
The commented-out println did not run, and the block comment in the middle of the expression was simply ignored.
2. Single-Line Comments
A single-line comment starts with // and runs to the end of the line. It is the most common kind of comment:
// Retry three times because the payment gateway sometimes times out
int maxRetries = 3;
double total = price * quantity; // tax is added later in checkout()
3. Multi-Line Comments
A multi-line comment starts with /* and ends with */. Everything between, across any number of lines, is ignored. The leading * on each line is only a style convention.
/*
* Prices are stored in paise (1 rupee = 100 paise) to avoid
* floating-point rounding errors. Convert to rupees only
* when displaying values to the user.
*/
long priceInPaise = 49_950;
/* a /* b */ c */, the comment ends at the first */, and c */ becomes a syntax error.4. Documentation Comments (Javadoc)
A Javadoc comment starts with /** and is placed directly before a class, interface, constructor, method or field. The javadoc tool turns these comments into HTML pages, the same format as the official Java API documentation, and IDEs show them as tooltips.
/**
* A simple calculator for basic arithmetic.
*
* <p>All methods are static, so no object is needed:
* {@code Calculator.divide(10, 2)}.</p>
*
* @author JavaByTechie
* @since 1.0
*/
public class Calculator {
/**
* Divides one integer by another.
*
* @param dividend the number to divide
* @param divisor the number to divide by; must not be zero
* @return the whole-number quotient
* @throws ArithmeticException if {@code divisor} is zero
* @see Math#floorDiv(int, int)
*/
public static int divide(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("divisor must not be zero");
}
return dividend / divisor;
}
public static void main(String[] args) {
System.out.println("17 / 5 = " + divide(17, 5));
}
}
17 / 5 = 3
The first sentence becomes the summary shown in method lists, so make it a complete, clear description.
5. Common Javadoc Tags
| Tag | Meaning |
|---|---|
@param name description | Describes a method or constructor parameter. |
@return description | Describes the return value. |
@throws Type description | Describes an exception the method may throw (@exception is a synonym). |
@see reference | Adds a "See Also" link to another class or method. |
@since version | The version in which the element was added. |
@deprecated explanation | Marks the element as deprecated and says what to use instead (use with the @Deprecated annotation). |
@author name | The author of a class. |
{@code text} | Formats text as code without interpreting HTML. |
{@link Class#method} | An inline link to another element. |
{@inheritDoc} | Copies documentation from the overridden method. |
{@snippet : ...} | Embeds a code example (Java 18+). |
6. Generating HTML Documentation
The JDK's javadoc tool reads your source files and produces a set of HTML pages:
javadoc -d docs Calculator.java # writes docs/index.html, docs/Calculator.html ...
# With Maven
mvn javadoc:javadoc
Javadoc warns about public elements that have no comment, which helps you keep a library's API fully documented. Java 23 also added support for writing Javadoc in Markdown using /// comments.
7. A Surprising Detail: Unicode Escapes in Comments
The compiler translates Unicode escapes such as \u000d (carriage return) before it removes comments. A line break hidden in a comment therefore ends the comment early, and the rest of the line is compiled as code:
public class UnicodeInComment {
public static void main(String[] args) {
// Unicode escapes are processed BEFORE comments are removed.
// \u000d System.out.println("Surprise: this line runs!");
System.out.println("Done");
}
}
Surprise: this line runs! Done
This is a popular interview puzzle. In real code, never put Unicode escapes for line breaks, quotes or backslashes in comments.
8. Writing Good Comments
- Explain why, not what. The code already shows what happens; the comment should give the reason, the business rule or the trade-off.
- Prefer clear names over comments.
int daysUntilExpiryneeds no comment;int d; // days until expirydoes. - Document public APIs with Javadoc: purpose, parameters, return value, exceptions and edge cases.
- Keep comments up to date. A wrong comment is worse than none.
- Do not leave dead code commented out; version control remembers old code for you.
- Use
TODOandFIXMEmarkers sparingly and with context; IDEs list them for you.
// Bad: repeats the code
i = i + 1; // add one to i
// Good: explains the reason
attempts++; // the API counts the first call as attempt 1, so start reporting from 1
9. Do Comments Affect Performance?
No. The compiler discards comments, so they never reach the .class file and have no effect on speed or size at runtime. Javadoc comments are only read by the javadoc tool and IDEs.
10. Summary
- Java has single-line (
//), multi-line (/* */) and documentation (/** */) comments. - Block comments cannot be nested.
- Javadoc comments with tags such as
@paramand@returngenerate HTML API documentation. - Comments do not affect the compiled program.
- Good comments explain intent and stay accurate; clear code needs fewer comments.
Related Tutorials
Reference: Oracle: Javadoc Guide
Frequently Asked Questions (FAQ)
Q1. What are comments in Java?
Comments are text in the source code that the compiler ignores. They explain the code to human readers, and Javadoc comments are also used to generate API documentation.
Q2. How many types of comments are there in Java?
Three: single-line comments (//), multi-line comments (/* ... */) and documentation comments (/** ... */).
Q3. What is the difference between /* */ and /** */?
Both are block comments ignored by the compiler. /** */ is a Javadoc comment that the javadoc tool and IDEs read to produce documentation; /* */ is just a regular comment.
Q4. Can comments be nested in Java?
Block comments cannot be nested; the first */ ends the comment. A // inside a block comment, or /* inside a // comment, is harmless because it is just text.
Q5. Do comments slow down a Java program?
No. Comments are removed during compilation and do not appear in the bytecode, so they have no runtime cost.
Q6. What is Javadoc?
Javadoc is both the comment format (/** ... */ with tags) and the JDK tool that converts those comments into HTML documentation pages.
Q7. How do I generate Javadoc?
Run javadoc -d docs YourClass.java, or use your build tool: mvn javadoc:javadoc for Maven or gradle javadoc for Gradle. IDEs also have a "Generate JavaDoc" command.
Q8. What does @param mean in Javadoc?
It documents one parameter of a method or constructor: @param divisor the number to divide by. Write one @param per parameter, in the same order as the parameter list.
Q9. What is the difference between @throws and @exception?
None; they are synonyms. @throws is the more common, modern form.
Q10. Where should Javadoc comments be placed?
Immediately before the declaration of a class, interface, enum, record, constructor, method or field, with only annotations allowed in between.
Q11. How do I comment out several lines quickly?
Select them in your IDE and press Ctrl + / (Cmd + / on macOS) to toggle // on each line. You can also wrap them in /* */, as long as they do not contain a block comment themselves.
Q12. Why can a comment containing \u000d execute code?
Unicode escapes are translated before the compiler identifies comments. \u000d becomes a line break, which ends a // comment, so the rest of the line is compiled as normal code.
Q13. Should every method have a comment?
Public methods of a library or shared API should have Javadoc. Private and obvious methods often do not need comments if their names and code are clear.
Q14. What is a TODO comment?
A marker like // TODO: handle network errors that reminds developers of unfinished work. IDEs collect TODO and FIXME comments into a task list.
Q15. Can I use HTML in Javadoc comments?
Yes. Javadoc accepts HTML tags such as <p>, <ul> and <b>. Use {@code ...} to show code without HTML interpretation.
Q16. Can I write Javadoc in Markdown?
Yes, since Java 23. Documentation comments that start with /// on each line are written in Markdown instead of HTML.
Q17. Are comments allowed anywhere in Java code?
Almost anywhere whitespace is allowed: between tokens, at the end of lines, between statements. They cannot appear inside string or character literals, where they would just be part of the text.
Q18. What is the @deprecated tag used for?
It explains in the documentation why an element should no longer be used and what to use instead. Combine it with the @Deprecated annotation so the compiler warns users.
Q19. Is it good practice to leave commented-out code?
No. It clutters the code and quickly becomes outdated. Delete it; version control such as Git keeps the history if you need it again.
Q20. Do comments appear in the compiled .class file?
No. The compiler drops all comments. Only annotations with suitable retention and debugging information such as line numbers can end up in class files.