Java Comments

Comments are notes in your code that Java ignores, used to explain what the code does or to temporarily disable lines.

Why comments matter

A comment is text the compiler skips entirely. Comments do not affect how a program runs; they exist to help people, including your future self, understand why the code was written a certain way. Good comments explain intent, not just repeat what the code obviously does.

Single-line comments

A single-line comment begins with two forward slashes. Everything from the slashes to the end of that line is ignored. You can place one on its own line or at the end of a line of code.

Single-line comments

public class Main {
  public static void main(String[] args) {
    // This line greets the user
    System.out.println("Hello, World!");
    System.out.println("Done"); // a trailing comment
  }
}

Multi-line comments

When a note spans several lines, wrap it between /* and */. Everything inside those markers is ignored, no matter how many lines it covers.

Multi-line comments

public class Main {
  public static void main(String[] args) {
    /*
      The lines below print a short greeting.
      This whole block is ignored by Java.
    */
    System.out.println("Hello, World!");
  }
}
StyleSyntaxBest for
Single-line// noteShort notes and quick explanations
Multi-line/* note */Longer explanations across several lines
Documentation/** note */Describing classes and methods for docs

Using comments to disable code

Comments are also handy while testing. By turning a line into a comment, you can temporarily stop it from running without deleting it. This is often called commenting out a line.

Commenting out a line

public class Main {
  public static void main(String[] args) {
    System.out.println("This line runs");
    // System.out.println("This line is skipped");
  }
}
Note: Write comments that explain why something is done, since the code itself already shows what is done. Avoid comments that simply restate the obvious.
Note: A special form, the documentation comment written as /** ... */, is used to generate official API documentation with a tool called Javadoc.

Exercise: Java Comments

Which symbol starts a single-line comment in Java?