Back to Study Material Java

Java Comments

Comments are portions of source code that the Java compiler completely ignores during compilation. They exist purely for human readers — to explain inten...

Java Comments

Writing Effective Comments in Java Code

Comments are portions of source code that the Java compiler completely ignores during compilation. They exist purely for human readers — to explain intent, document APIs, mark areas for future improvement, or temporarily disable code during debugging. Good commenting habits are a mark of professional software development because code is read far more often than it is written.

Java provides three types of comments, each suited to a different purpose. The single-line comment starts with two forward slashes (//) and continues to the end of that line. It is ideal for brief explanations next to a statement: int maxRetries = 3; // Retry up to three times before failing. Single-line comments are the most common type in everyday code.

The multi-line comment (also called a block comment) starts with /* and ends with */. It can span any number of lines and is useful for longer explanations or for temporarily commenting out large blocks of code during development. Example: /* This section handles database connection pooling. It will be replaced with a connection pool library in a future release. */. Note that multi-line comments cannot be nested; a /* inside another /* does not create a new level of nesting.

Javadoc comments start with /** (note the double asterisk) and end with */. They are processed by the javadoc tool to generate HTML API documentation automatically. Javadoc comments appear immediately before the class, method, or field they describe. Standard tags include @param to describe a method parameter, @return to describe the return value, @throws to describe exceptions the method may throw, and @author to credit the author. Example: /** Returns the area of a circle. @param radius the radius of the circle. @return the computed area as a double. */

Effective comments explain why code does something, not what it does. If the code itself clearly shows what is happening (e.g., i++), a comment saying "increment i" adds no value. A useful comment might instead say why i must be incremented before the check rather than after.

Exam tip: Know that Javadoc comments are only processed for public and protected members by default. Private members are not included in generated documentation unless you run javadoc with the -private flag. This is a detail that appears in Java certification exams.