Comments: Write Code Humans Can Read

Introduction

In this chapter, you will learn how to use comments in Java to explain intent and document APIs. Comments do not affect compilation or runtime behavior (except when using special tools that read documentation comments), but they are essential for communication between developers. Good comments help future you and your teammates understand why code exists.

This pairs with Coding Standards: clear names first, comments when intent is not obvious.

Prerequisites

  • JDK 21 and a working main class
  • Basic understanding of Variables
  • Familiarity with running code in IntelliJ or the terminal

What Is a Comment

A comment is text the compiler ignores. You write comments for humans, not for the JVM.

Java has three common comment forms:

  • // single-line
  • /* ... */ multi-line
  • /** ... */ documentation (Javadoc)

1) Single-Line Comments

Use // for short notes on their own line or at the end of a line.

java
public class CommentDemo {
    public static void main(String[] args) {
        // Store user name for greeting message
        String userName = "Alice";
 
        // Print welcome message
        System.out.println("Welcome, " + userName + "!");
    }
}

This is the most common style in daily coding.

2) Inline Comments (Use Sparingly)

Inline comments sit on the same line as code.

java
int score = 95;  // Final exam score

Use them only when they add quick context. Avoid repeating what the code already says.

Tip

Best Practice

Comment the why, not the obvious what.
If totalPrice = unitPrice * quantity is self-explanatory, you usually do not need a comment—unless a business rule requires explanation.

3) Multi-Line Comments

Use /* ... */ for longer explanations or temporarily disabling blocks during experiments.

java
/*
 * Business rule for discounts:
 * - VIP users: 20% off
 * - New users: 10% off
 * - Others: no discount
 */
double discount = 0.0;
boolean isVip = true;
 
if (isVip) {
    discount = 0.2;
}

Warning

Do not leave large blocks of commented-out code in shared projects. Delete dead code or rely on version control (Git) to recover old versions.

4) Documentation Comments (Javadoc)

Use /** ... */ immediately before public classes, methods, and fields you want to document for others (and for IDE tooltips).

java
/**
 * Returns total payment before discount.
 *
 * @param price    unit price in cents
 * @param quantity number of items
 * @return total before discount
 */
public static int calculateTotal(int price, int quantity) {
    return price * quantity;
}

Common Javadoc tags (learn gradually):

TagPurpose
@paramDescribes a method parameter
@returnDescribes return value
@throwsDescribes exceptions the method may throw

Difference:

  • Comment: free-form note for readers; ignored by compiler
  • Javadoc: structured documentation; IDEs and javadoc tool can render HTML docs from it

You do not need Javadoc on every private helper while learning—use it on reusable public APIs.

5) Real Mini Example: Learning Tracker

Practical comments on a small program using variables from the previous chapter:

java
public class LearningTracker {
    public static void main(String[] args) {
        // Secret target days for "course complete" badge
        final int targetDays = 30;
 
        int learningDays = 9;
 
        // Encourage user without exposing internal target in output
        if (learningDays < targetDays) {
            int daysLeft = targetDays - learningDays;
            System.out.println("Keep going! " + daysLeft + " days to your goal.");
        } else {
            System.out.println("Goal reached—great discipline!");
        }
    }
}

Comment Quality Checklist

  • Keep comments short and specific
  • Update comments when code changes
  • Prefer clear names over comment noise
  • Remove outdated comments immediately

Outdated comments are worse than no comments—they lie to the reader.

Common Beginner Mistakes

Commenting Every Line

Too many comments create visual noise.

java
// Declare name
String name = "Tom";
// Print name
System.out.println(name);

Usually unnecessary if names are clear.

Using Comments to Fix Bad Names

Bad:

java
int d;  // days since login

Better:

java
int daysSinceLogin = 0;

Nesting /* Inside /* Carelessly

The first */ closes the block. For long disabled experiments, prefer // on each line or use Git instead of huge comment blocks.

What’s Next

With variables and comments in place, learn how to compute and compare values in Operators.

FAQ

Do comments affect performance?

No. The compiler discards normal comments. Javadoc is also ignored at runtime.

Should every method have Javadoc?

Not while learning. Add Javadoc when you write public methods others (or future you) will call from outside the class.

Can comments replace good variable names?

No. Naming is the first layer of readability; comments support it, they do not replace it.

What language should comments use?

Match your team or course. This tutorial uses English in code and docs; your inline comments can follow the same rule for consistency.

Is // inside a string a comment?

No. Inside quotes, // is just text:

java
String url = "https://example.com";  // only this part is a comment