Java Tutorial
🔍

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:

Java
1int r = d * 1000 / t;

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

Now with a comment:

Java
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:

Java
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.

Java
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:

Java
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.

Java
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:

Java
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:

Java
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:

Java
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:

Java
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:

Java
1/** 2 * The maximum number of login attempts before the account is locked. 3 */ 4static 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

Java
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:

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

Why a decision was made:

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

Legal or business rules:

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

Complex algorithms:

Java
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:

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

Don't Comment This ❌

What the code obviously does:

Java
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 already

Repeating the variable name:

Java
1int age = 25; // age is 25 ❌

Explaining Java syntax to experienced readers:

Java
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.

Java
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() 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

Java
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

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

TopicLink
Syntax & structure — the rules of Java codeSyntax & Structure →
Methods — where Javadoc is most commonly usedDefining Methods →
Classes and objects — class-level JavadocClasses & Objects →
Best practices — writing clean, readable codeClean Code in Java →
Comments | DevStackFlow