Java Comments and Code Structure

Java comments explain source code without becoming executable instructions.

Lesson 4 of 127Beginner13 min read

Java comments explain source code without becoming executable instructions. A single-line comment begins with //, a block comment uses /* and /, and a documentation comment begins with /*. Choose the form according to the reader and purpose: a short explanation beside a calculation differs from documentation for someone calling a public method.

Good comments explain decisions that names and statements cannot express clearly. They should help a learner understand the program rather than narrate every punctuation mark. The examples below distinguish ordinary comments from documentation and show how file organization makes both easier to follow.

Single-line comments and useful intent

Everything after // on the same source line is a comment, unless those characters appear inside a string literal. Place a short comment above a statement when it explains a rule or a deliberate choice. An end-of-line comment can explain a small detail, but long notes are easier to read on their own lines.

For example, // Round up because a partly filled tray still needs a label explains why a calculation uses a particular rounding rule. By contrast, // Add one above count++ simply repeats the instruction. Prefer a meaningful variable name when a comment exists only to translate an abbreviation.

Block comments and their limits

A block comment begins with /* and continues until the next /. It can span multiple lines. Java ignores its text when compiling, but comments still need a valid ending. Forgetting / can cause a compilation failure or make intended source code disappear into the comment.

Block comments do not nest. If you surround code that already contains a block comment with another /* ... */, the inner closing marker ends the outer comment. Prefer your editor’s line-comment command when temporarily disabling several lines. Do not leave large blocks of obsolete code in a maintained file: version control already records old versions, while unused fragments make the active behavior harder to identify. For a deliberate learning comparison, keep each version in a clearly labeled example instead.

Javadoc describes a contract

A documentation comment starts with /** and appears immediately before the class, constructor, method or field it documents. The javadoc tool can extract these comments into HTML documentation. Ordinary // and /* comments are useful to source readers but do not provide the same documentation structure.

A method comment should state what the method computes, what its parameters mean and what callers receive. The @param tag documents a named parameter, and @return documents a returned result. Use @throws when a particular exception is part of the contract. These tags describe behavior; they do not enforce it. A comment promising that a method rejects negative values must match the implementation. Document important units and boundaries, such as minutes rather than seconds, because a correct type alone cannot express that distinction.

Organize a source file for its readers

A conventional Java source file starts with an optional package declaration, then import declarations, then its type declarations. Within a small class, fields commonly appear before constructors and methods. This arrangement is a readable convention rather than a requirement that every method follow a specific ordering. A public top-level class must match its filename.

Use consistent indentation so that class, method and conditional boundaries are visible. Keep one statement per line in beginner examples. Separate distinct steps with a modest amount of whitespace. Imports shorten type names but should remain specific enough that readers can find dependencies. A source file with no package belongs to the unnamed package; that is convenient for these small programs, while real projects normally use named packages. Do not add a package line to only one file without adjusting its location and launch command.

Comments are not runtime output

Java does not print a comment merely because it contains readable words. To display a message, call a printing method explicitly. A comment can contain Java-like text without compiling that text, provided the comment boundaries remain valid. Similarly, a string containing "//" represents two slash characters and is not a comment.

Practice with explained solutions

Task 1. Add a useful comment explaining why a shop rounds a delivery count upward when one package remains.

Solution. Explain the business rule: every started delivery box needs its own label. Do not merely describe the division operator.

Task 2. Write a Javadoc comment for a method int square(int value).

Solution. Describe that it returns value multiplied by itself, add @param value and @return, and mention accepted range if overflow matters to the application.

Java Summary

  • Use comments to explain a reason or constraint that the code cannot express clearly.
  • Block comments do not nest, and comment markers inside strings remain ordinary text.
  • Javadoc comments document declarations; ordinary comments do not appear in program output.
  • Continue with Java syntax.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Explain a rounding decision

Save this complete program as TrayLabels.java. Compile with javac --release 17 TrayLabels.java and run with java TrayLabels.

Java
public class TrayLabels {
    public static void main(String[] args) {
        int seedlings = 10;
        int capacity = 4;
        // A partially occupied tray also needs one label.
        int labels = (seedlings + capacity - 1) / capacity;
        System.out.println(labels);
    }
}
Output
3
Line-by-line explanation
  1. Lines 1 to 9The calculation uses integer division after increasing the numerator by capacity - 1. With ten seedlings and room for four per tray, two full trays and one partial tray require three labels. The comment explains why rounding upward is intended. It does not supply a value to the expression or appear in the output. Changing seedlings to eight should produce two, so test that exact-fit boundary as well.
Example 2

Recognize comment markers inside text

Save this complete program as CommentText.java. Compile with javac --release 17 CommentText.java and run with java CommentText.

Java
public class CommentText {
    public static void main(String[] args) {
        // This source comment is not printed.
        System.out.println("https://example.test");
        /* The next output contains slash characters, not a source comment. */
        System.out.println("Use // for a line comment");
    }
}
Output
https://example.test
Use // for a line comment
Line-by-line explanation
  1. Lines 1 to 8The compiler interprets the slash pairs inside double quotes as string content. Both println calls therefore execute normally. The real comments outside the strings are ignored for execution. Notice that the web address does not end the statement early. Source syntax must be interpreted in context: a character sequence inside a literal can have a different meaning from the same sequence in executable source.
Example 3

Document and call a method

Save this complete program as MinuteConversion.java. Compile with javac --release 17 MinuteConversion.java and run with java MinuteConversion.

Java
public class MinuteConversion {
    /** Converts whole minutes to seconds.
     * @param minutes number of whole minutes
     * @return the equivalent number of seconds
     */
    static int seconds(int minutes) {
        return minutes * 60;
    }
    public static void main(String[] args) {
        System.out.println(seconds(7));
    }
}
Output
420
Line-by-line explanation
  1. Lines 1 to 8This example places a documentation comment directly above seconds. The @param name matches the parameter in the signature, and @return describes the unit of the result.
  2. Lines 9 to 12The call supplies seven minutes, so multiplication by sixty returns 420 seconds. The example uses small values; an int multiplication can overflow for very large inputs, so a production contract should also define an accepted range or use an appropriate wider calculation.

Common Java Mistakes

Comments that disagree with the code

Do not write a confident comment that disagrees with the code. If a discount changes from ten percent to fifteen percent, update both the calculation and its explanation. Avoid comments that merely state Print result or Create variable; they add reading work without clarifying behavior. Reserve detailed documentation for a meaningful contract, not a paragraph repeated above every simple getter.

Java FAQ

Can comments fix a compiler error?

They can temporarily remove source from compilation, but they do not repair invalid active code. Restore and correct the statement rather than permanently hiding a necessary operation.

Must every method have Javadoc?

No. Public APIs benefit from documented contracts, while a small private helper with an obvious purpose may need little explanation. Follow project requirements and document behavior that callers cannot infer safely.

Do comments make a Java program slower or bigger?

No. The compiler discards comments, so they don't appear in the .class files and have no effect on speed or size when the program runs. Write as many useful comments as the code needs.

How do I turn Javadoc comments into a web page?

Run the javadoc tool from the JDK, for example javadoc -d docs Greeting.java, which writes HTML pages into a docs folder. Build tools have the same feature: mvn javadoc:javadoc with Maven, or the javadoc task in Gradle.

Should I leave TODO comments in my code?

A short // TODO is a helpful marker, and most IDEs list them in one place. Don't let them pile up: add enough detail to act on it, and move larger pieces of work into an issue tracker so they aren't forgotten.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Why is // Round up for a partial tray useful?

Multiple choicemedium

Which tag documents a method parameter?

Java Quiz

2 questions to check what you learned.

  1. Which comment supports generated API documentation?

    • /** ... */
    • // ...
    • A printed string
  2. Can ordinary block comments nest?

    • No
    • Yes, without limits
    • Only inside main