๐ŸŽ“ A1Learner
๐Ÿ”

Java Comments

A comment is a note in Java code that the compiler ignores. Comments explain the code to people who read it.

A program without comments

This plain program prints one greeting. Its output is the base for the next program.

public class Main {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}

The same program with a comment

A line comment sits above the println line. The output is the same as the plain program.

public class Main {
  public static void main(String[] args) {
    // Print a greeting
    System.out.println("Hello, World!");
  }
}

A commented-out line does not run

The first println line is inside a comment. Only the second println line runs.

public class Main {
  public static void main(String[] args) {
    // System.out.println("This line does not print");
    System.out.println("This line prints");
  }
}

A comment over many lines

The block comment spans two lines before the println line. The greeting still prints.

public class Main {
  public static void main(String[] args) {
    /* A greeting program
       It prints one line. */
    System.out.println("Hello, World!");
  }
}

Example

public class Main {
  public static void main(String[] args) {
    // Print the first line
    System.out.println("Welcome");
    /* Print the second line
       The comment itself prints nothing. */
    System.out.println("Comments do not print");
  }
}

Key points

  • Two slashes start a comment that runs to the end of the line.
  • Slash and star marks start a comment that can span many lines.
  • Star and slash marks end a multi-line comment.
  • A commented program prints the same output as the same program without comments.
  • A commented-out statement does not run.
  • Comments are invisible to the compiler.

In this example, the program carries a line comment and a block comment. Neither comment prints. The two println lines print Welcome and Comments do not print in order.

Note

Comments print nothing at all.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

What does the compiler do with a comment?