← Back to Core Java Course | Chapter 1: Introduction & Basics | Lesson 6 of 12

Java Comments

Single-Line Comments

A // comment runs from that point to the end of the line, making it ideal for short, one-line notes explaining a tricky piece of logic right next to the code it describes.

Example: Single-Line Comments

java
public class Main {
	public static void main(String[] args) {
		int total = 100; // running total for the cart
		System.out.println(total);
	}
}

Multi-Line Comments

A /* ... */ block comment can span multiple lines, which is useful for temporarily disabling a chunk of code or writing a longer explanation above a complex method.

Example: Multi-Line Comments

java
public class Main {
	/*
	 * This block comment can span
	 * multiple lines of explanation.
	 */
	public static void main(String[] args) {
		System.out.println("See the block comment above.");
	}
}

Javadoc Comments

Javadoc comments (/** ... */) placed above a class or method get picked up by the javadoc tool to auto-generate browsable HTML API documentation -- this is how Java's own standard library docs are built.

Example: Javadoc Comments

java
public class Main {
	/**
	 * Adds two integers together.
	 * @param a first number
	 * @param b second number
	 * @return the sum of a and b
	 */
	static int add(int a, int b) {
		return a + b;
	}
	public static void main(String[] args) {
		System.out.println(add(2, 3));
	}
}

Commenting Out Code

Wrapping code in // or /* */ during debugging lets you quickly rule out whether a specific block is causing a bug, without deleting and having to retype it afterward.

Example: Commenting Out Code

java
public class Main {
	public static void main(String[] args) {
		System.out.println("Active line");
		// System.out.println("Disabled while debugging");
	}
}

Comment Best Practices

Stale comments that no longer match the code they describe are worse than no comment at all, since they actively mislead the next reader -- update or delete them whenever you change the logic nearby.

Example: Comment Best Practices

java
public class Main {
	public static void main(String[] args) {
		int price = 20; // price in dollars (kept in sync with the code beside it)
		System.out.println(price);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.