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:
1int r = d * 1000 / t;Without context, this is meaningless. What is r? What does d * 1000 / t calculate?
Now with a comment:
1// Convert distance (km) and time (s) to speed in metres per second
2int 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:
1// Apply 18% GST — mandated by Finance Act 2023
2double 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.
1// This is a single-line comment
2
3int age = 25; // age of the student — must be between 18 and 60
4
5// Multiply by 100 to convert decimal to percentage
6double percentage = (double) correct / total * 100;Three ways to use it:
1// 1. On its own line — explains what follows
2// Calculate the discounted price
3double discounted = price * (1 - discount);
4
5// 2. End of line — adds context to a specific statement
6int MAX_SIZE = 100; // cannot exceed database column limit
7
8// 3. Temporarily disable code during debugging
9// 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.
1/*
2 This method calculates the compound interest.
3 Formula: A = P(1 + r/n)^(nt)
4 where:
5 P = principal amount
6 r = annual interest rate (decimal)
7 n = times compounded per year
8 t = time in years
9*/
10double compoundInterest = principal * Math.pow(1 + rate / n, n * time);Commenting out a block of code:
1/*
2System.out.println("Temporary debug output");
3System.out.println("Balance: " + balance);
4System.out.println("Rate: " + rate);
5*/💡 Multi-line comments cannot be nested. The first */ closes the comment, regardless of any /* inside it:
1/*
2 Outer comment starts
3 /* this does NOT start a new comment */ ← this closes the outer comment!
4 This line is NO LONGER a comment — compiler reads it
5*/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:
1/**
2 * Calculates the area of a rectangle.
3 *
4 * @param width the width of the rectangle in centimetres
5 * @param height the height of the rectangle in centimetres
6 * @return the area in square centimetres
7 */
8public double calculateArea(double width, double height) {
9 return width * height;
10}For a class:
1/**
2 * Represents a bank account with basic deposit and withdrawal operations.
3 * Each account has a unique account number and tracks the current balance.
4 *
5 * @author Arjun Kumar
6 * @version 1.0
7 */
8public class BankAccount {
9 // ...
10}For a field:
1/**
2 * The maximum number of login attempts before the account is locked.
3 */
4static final int MAX_LOGIN_ATTEMPTS = 3;Common Javadoc Tags
| Tag | Purpose | Example |
|---|---|---|
@param | Describes a method parameter | @param name the student's full name |
@return | Describes the return value | @return the calculated tax amount |
@throws | Documents an exception | @throws IllegalArgumentException if age is negative |
@author | Names the code's author | @author Priya Sharma |
@version | Documents the version | @version 2.1 |
@see | References related class or method | @see BankAccount#withdraw |
@since | When 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
1import java.util.Scanner;
2
3/**
4 * A simple calculator that adds two numbers entered by the user.
5 * Demonstrates all three types of Java comments.
6 *
7 * @author DevStackFlow
8 * @version 1.0
9 */
10public class Calculator {
11
12 /* Maximum value allowed for input.
13 Prevents integer overflow in calculations. */
14 static final int MAX_VALUE = 1_000_000;
15
16 /**
17 * Reads two integers from the user and prints their sum.
18 *
19 * @param args command-line arguments (not used)
20 */
21 public static void main(String[] args) {
22
23 Scanner scanner = new Scanner(System.in);
24
25 // Prompt and read first number
26 System.out.print("Enter first number: ");
27 int a = scanner.nextInt();
28
29 // Prompt and read second number
30 System.out.print("Enter second number: ");
31 int b = scanner.nextInt();
32
33 int sum = a + b; // add the two values
34
35 System.out.println("Sum: " + sum);
36
37 scanner.close();
38 }
39}What to Comment — And What Not to
This is the most important skill — knowing when a comment adds value.
Comment This ✅
Non-obvious logic:
1// Offset by 1 because array index starts at 0 but display starts at 1
2int displayIndex = arrayIndex + 1;Why a decision was made:
1// Using LinkedList instead of ArrayList — we need O(1) insertions at both ends
2LinkedList<Integer> queue = new LinkedList<>();Legal or business rules:
1// Minimum age for alcohol purchase — as per Indian Excise Act
2if (age < 21) {
3 return false;
4}Complex algorithms:
1// Binary search: divide the array in half each iteration
2// Time complexity: O(log n)
3int mid = left + (right - left) / 2;Workarounds or known issues:
1// TODO: replace with proper validation once backend API is updated
2if (input.length() > 0) { ... }Don't Comment This ❌
What the code obviously does:
1// Add 1 to count
2count++; // ❌ this comment adds nothing
3
4// Declare a variable called name
5String name = "Arjun"; // ❌ the code says exactly this alreadyRepeating the variable name:
1int age = 25; // age is 25 ❌Explaining Java syntax to experienced readers:
1// for loop that runs 10 times
2for (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.
1// TODO: add input validation
2// TODO: handle the case where the file doesn't exist
3// TODO: replace hardcoded URL with config value
4// FIXME: this calculation is wrong for negative numbers
5// FIXME: memory leak in the loop below
6// NOTE: this method is deprecated — use calculateV2() insteadIn 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
| Action | VS Code | IntelliJ |
|---|---|---|
| Toggle single-line comment | Ctrl+/ (Cmd+/ Mac) | Ctrl+/ (Cmd+/ Mac) |
| Toggle block comment | Shift+Alt+A | Ctrl+Shift+/ |
| Select multiple lines, then comment | Select → Ctrl+/ | Select → Ctrl+/ |
| Generate Javadoc template | Type /** + Enter above a method | Type /** + 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
1import java.util.Scanner;
2
3/**
4 * Calculates the final exam grade based on marks entered by the user.
5 * Uses a standard grading scale: A (90+), B (75+), C (60+), F (below 60).
6 */
7public class GradeCalculator {
8
9 // Grading thresholds — adjust if institution changes the scale
10 static final int A_THRESHOLD = 90;
11 static final int B_THRESHOLD = 75;
12 static final int C_THRESHOLD = 60;
13
14 /**
15 * Reads student marks and displays the corresponding grade.
16 *
17 * @param args command-line arguments (not used)
18 */
19 public static void main(String[] args) {
20
21 Scanner scanner = new Scanner(System.in);
22
23 System.out.print("Enter marks (0-100): ");
24 int marks = scanner.nextInt();
25
26 // Determine grade based on marks
27 String grade;
28 if (marks >= A_THRESHOLD) {
29 grade = "A";
30 } else if (marks >= B_THRESHOLD) {
31 grade = "B";
32 } else if (marks >= C_THRESHOLD) {
33 grade = "C";
34 } else {
35 grade = "F"; // below passing threshold
36 }
37
38 System.out.println("Grade: " + grade);
39
40 scanner.close();
41
42 // TODO: extend to handle multiple subjects and calculate average
43 }
44}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
| Mistake | Example | Why It's a Problem |
|---|---|---|
| Commenting obvious code | // increment i before i++ | Adds clutter, wastes reading time |
| Outdated comments | Comment says "returns false" but code returns true | Worse than no comment — actively misleads |
Nested /* */ | /* outer /* inner */ */ | First */ closes everything — syntax error or wrong behaviour |
| No Javadoc on public methods | Public API with no description | Other developers can't use your code without reading it line by line |
| Commented-out code left permanently | Dozens of // old code blocks | Use version control (Git) instead — delete the code, keep the history |
The 3 Things to Remember From This Page
- ›Three types:
//for single lines,/* */for blocks,/** */for Javadoc documentation. Each has its place — use the right one for the context. - ›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.
- ›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.
- ›
TODOandFIXME— 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
| Topic | Link |
|---|---|
| Syntax & structure — the rules of Java code | Syntax & Structure → |
| Methods — where Javadoc is most commonly used | Defining Methods → |
| Classes and objects — class-level Javadoc | Classes & Objects → |
| Best practices — writing clean, readable code | Clean Code in Java → |