Java Tutorial
🔍

Java Comments

A comment is a line — or block of lines — that the compiler completely ignores.

Comments exist for one reason: to help humans understand the code. They have zero effect on how the program runs. You can add a thousand comments and the compiled output stays identical.

Yet good comments are one of the clearest marks of a professional developer. They explain intent, document decisions, and make code readable to anyone — including yourself six months from now.

👉 What you'll learn here:

  • ›The three types of comments in Java
  • ›When and how to write comments effectively
  • ›Javadoc — turning comments into documentation
  • ›What not to comment — and why over-commenting hurts
  • ›Comment shortcuts in your editor

🧘 Comments are the easiest thing in Java to learn.

The syntax is three patterns you'll memorize in minutes. The harder skill — knowing when and what to comment — comes with practice. This page covers both.

Why Comments Matter

Consider this code:

int r = d * 1000 / t;

Without context, this is meaningless. What is r? What does d * 1000 / t calculate?

Now with a comment:

// Convert distance (km) and time (s) to speed in metres per second int r = d * 1000 / t;

Instantly clear. The comment tells you the why and the what — things the code itself cannot always express.

Good naming helps too — but even well-named variables sometimes need context:

// Apply 18% GST — mandated by Finance Act 2023 double finalPrice = basePrice * 1.18;

The code tells you what is happening. The comment tells you why — a legal requirement that someone reading the code six months later needs to know.

Type 1 — Single-Line Comment //

The most common comment. Everything after // on that line is ignored by the compiler.

// This is a single-line comment int age = 25; // age of the student — must be between 18 and 60 // Multiply by 100 to convert decimal to percentage double percentage = (double) correct / total * 100;

Three ways to use it:

// 1. On its own line — explains what follows // Calculate the discounted price double discounted = price * (1 - discount); // 2. End of line — adds context to a specific statement int MAX_SIZE = 100; // cannot exceed database column limit // 3. Temporarily disable code during debugging // System.out.println("Debug: " + value);

💡 Keyboard shortcut: In VS Code and IntelliJ, press Ctrl + / (Windows/Linux) or Cmd + / (Mac) to toggle a comment on the current line. Select multiple lines first to comment them all at once. This is one of the most-used shortcuts in daily development.

Type 2 — Multi-Line Comment /* ... */

Used when a comment spans multiple lines. Everything between /* and */ is ignored.

/* This method calculates the compound interest. Formula: A = P(1 + r/n)^(nt) where: P = principal amount r = annual interest rate (decimal) n = times compounded per year t = time in years */ double compoundInterest = principal * Math.pow(1 + rate / n, n * time);

Commenting out a block of code:

/* System.out.println("Temporary debug output"); System.out.println("Balance: " + balance); System.out.println("Rate: " + rate); */

💡 Multi-line comments cannot be nested. The first */ closes the comment, regardless of any /* inside it:

/* Outer comment starts /* this does NOT start a new comment */ ← this closes the outer comment! This line is NO LONGER a comment — compiler reads it */

Avoid putting /* inside a multi-line comment. If you need to comment out code that already contains comments, use // on each line instead.

Type 3 — Javadoc Comment /** ... */

Javadoc comments are a special form of multi-line comment that Java's documentation tool (javadoc) can read and convert into HTML documentation pages — the same format used by Java's official API documentation.

They start with /** (two asterisks) and are placed directly above the class, method, or field they describe.

For a method:

/** * Calculates the area of a rectangle. * * @param width the width of the rectangle in centimetres * @param height the height of the rectangle in centimetres * @return the area in square centimetres */ public double calculateArea(double width, double height) { return width * height; }

For a class:

/** * Represents a bank account with basic deposit and withdrawal operations. * Each account has a unique account number and tracks the current balance. * * @author Arjun Kumar * @version 1.0 */ public class BankAccount { // ... }

For a field:

/** * The maximum number of login attempts before the account is locked. */ static final int MAX_LOGIN_ATTEMPTS = 3;

Common Javadoc Tags

TagPurposeExample
@paramDescribes a method parameter@param name the student's full name
@returnDescribes the return value@return the calculated tax amount
@throwsDocuments an exception@throws IllegalArgumentException if age is negative
@authorNames the code's author@author Priya Sharma
@versionDocuments the version@version 2.1
@seeReferences related class or method@see BankAccount#withdraw
@sinceWhen this was added@since Java 8

💡 You'll see Javadoc constantly when reading Java library documentation. Every method in String, ArrayList, Scanner — all documented with Javadoc. Writing it for your own code is what separates professional code from student code.

All Three Types — Side by Side

import java.util.Scanner; /** * A simple calculator that adds two numbers entered by the user. * Demonstrates all three types of Java comments. * * @author DevStackFlow * @version 1.0 */ public class Calculator { /* Maximum value allowed for input. Prevents integer overflow in calculations. */ static final int MAX_VALUE = 1_000_000; /** * Reads two integers from the user and prints their sum. * * @param args command-line arguments (not used) */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Prompt and read first number System.out.print("Enter first number: "); int a = scanner.nextInt(); // Prompt and read second number System.out.print("Enter second number: "); int b = scanner.nextInt(); int sum = a + b; // add the two values System.out.println("Sum: " + sum); scanner.close(); } }

What to Comment — And What Not to

This is the most important skill — knowing when a comment adds value.

Comment This ✅

Non-obvious logic:

// Offset by 1 because array index starts at 0 but display starts at 1 int displayIndex = arrayIndex + 1;

Why a decision was made:

// Using LinkedList instead of ArrayList — we need O(1) insertions at both ends LinkedList<Integer> queue = new LinkedList<>();

Legal or business rules:

// Minimum age for alcohol purchase — as per Indian Excise Act if (age < 21) { return false; }

Complex algorithms:

// Binary search: divide the array in half each iteration // Time complexity: O(log n) int mid = left + (right - left) / 2;

Workarounds or known issues:

// TODO: replace with proper validation once backend API is updated if (input.length() > 0) { ... }

Don't Comment This ❌

What the code obviously does:

// Add 1 to count count++; // ❌ this comment adds nothing // Declare a variable called name String name = "Arjun"; // ❌ the code says exactly this already

Repeating the variable name:

int age = 25; // age is 25 ❌

Explaining Java syntax to experienced readers:

// for loop that runs 10 times for (int i = 0; i < 10; i++) { // ❌ any Java developer knows what a for loop is

💡 The golden rule: If removing the comment makes the code harder to understand, keep it. If removing it makes no difference — because the code already explains itself — remove it. Comments should explain why, not repeat what.

The TODO Comment — A Special Convention

TODO is a widely recognized comment convention used by developers everywhere — and supported by most IDEs which highlight and list them automatically.

// TODO: add input validation // TODO: handle the case where the file doesn't exist // TODO: replace hardcoded URL with config value // FIXME: this calculation is wrong for negative numbers // FIXME: memory leak in the loop below // NOTE: this method is deprecated — use calculateV2() instead

In VS Code and IntelliJ, TODOs appear highlighted and show up in a dedicated panel — making them easy to track as a task list within your code.

Comment Shortcuts — Editor Tips

ActionVS CodeIntelliJ
Toggle single-line commentCtrl+/ (Cmd+/ Mac)Ctrl+/ (Cmd+/ Mac)
Toggle block commentShift+Alt+ACtrl+Shift+/
Select multiple lines, then commentSelect → Ctrl+/Select → Ctrl+/
Generate Javadoc templateType /** + Enter above a methodType /** + Enter above a method

💡 Javadoc auto-generation: In both VS Code and IntelliJ, if you type /** on the line directly above a method and press Enter, the editor automatically generates the Javadoc template with @param tags for each parameter and @return if the method returns a value. You just fill in the descriptions.

A Complete Example — Well-Commented Code

import java.util.Scanner; /** * Calculates the final exam grade based on marks entered by the user. * Uses a standard grading scale: A (90+), B (75+), C (60+), F (below 60). */ public class GradeCalculator { // Grading thresholds — adjust if institution changes the scale static final int A_THRESHOLD = 90; static final int B_THRESHOLD = 75; static final int C_THRESHOLD = 60; /** * Reads student marks and displays the corresponding grade. * * @param args command-line arguments (not used) */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter marks (0-100): "); int marks = scanner.nextInt(); // Determine grade based on marks String grade; if (marks >= A_THRESHOLD) { grade = "A"; } else if (marks >= B_THRESHOLD) { grade = "B"; } else if (marks >= C_THRESHOLD) { grade = "C"; } else { grade = "F"; // below passing threshold } System.out.println("Grade: " + grade); scanner.close(); // TODO: extend to handle multiple subjects and calculate average } }

This example demonstrates:

  • ›A Javadoc class comment explaining the program's purpose
  • ›Constants with end-of-line comments explaining why they exist separately
  • ›A Javadoc method comment with @param
  • ›Inline comments explaining logic, not syntax
  • ›A TODO for future improvement

Common Comment Mistakes

MistakeExampleWhy It's a Problem
Commenting obvious code// increment i before i++Adds clutter, wastes reading time
Outdated commentsComment says "returns false" but code returns trueWorse than no comment — actively misleads
Nested /* *//* outer /* inner */ */First */ closes everything — syntax error or wrong behaviour
No Javadoc on public methodsPublic API with no descriptionOther developers can't use your code without reading it line by line
Commented-out code left permanentlyDozens of // old code blocksUse version control (Git) instead — delete the code, keep the history

The 3 Things to Remember From This Page

  1. ›Three types: // for single lines, /* */ for blocks, /** */ for Javadoc documentation. Each has its place — use the right one for the context.
  2. ›Comment the why, not the what — the code already shows what it does. Comments add value when they explain the reason behind a decision, a business rule, or non-obvious logic.
  3. ›Outdated comments are worse than no comments — a comment that contradicts the code actively misleads every reader. When you change code, update or delete its comments immediately.

Summary

  • ›// — single-line comment. Most common. Use for brief explanations and end-of-line notes.
  • ›/* ... */ — multi-line comment. Use for longer explanations or commenting out code blocks. Cannot be nested.
  • ›/** ... */ — Javadoc comment. Use above classes, methods, and fields. Generates official HTML documentation.
  • ›Common Javadoc tags: @param, @return, @throws, @author, @version
  • ›Comment the why — explain decisions, rules, and non-obvious logic. Don't repeat what the code already says.
  • ›TODO and FIXME — widely recognized conventions, highlighted by IDEs, useful for tracking future work.
  • ›Outdated comments mislead — always update comments when you change the code they describe.
  • ›Editor shortcuts: Ctrl+/ toggles line comments in both VS Code and IntelliJ.

What to Read Next

Practice Programs

Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.

Browse all Java programs →