Understanding Java Comments

In Java, comments are used to add explanatory notes within the code. Comments are ignored by the compiler and do not affect the program's execution. They are useful for providing information to developers or for temporarily excluding code during development.

Single-Line Comments

Single-line comments start with // and extend until the end of the line. They are commonly used for short explanations or notes on a single line of code.

// This is a single-line comment

Multi-Line Comments

Multi-line comments start with /* and end with */. They can span multiple lines and are suitable for longer explanations or commenting out blocks of code.


/*
  This is a multi-line comment
  It can span multiple lines
*/

Example:

Let's consider a simple Java program with comments:


public class HelloWorld {

  // main method - entry point of the program
  public static void main(String[] args) {

    // Print "Hello, World!" to the console
    System.out.println("Hello, World!");

    /*
      The following code calculates and prints the sum of two numbers
      int num1 = 5;
      int num2 = 7;
      int sum = num1 + num2;
      System.out.println("Sum: " + sum);
    */

  }
}

In this example, single-line and multi-line comments are used to provide explanations for different parts of the code.

Note:

It is considered a good practice to use comments in your Java code. Clear and informative comments enhance code readability and make it easier for developers to understand the purpose and functionality of the code.