Have a question?
Message sent Close
View Categories

What is Java Comments ?

What is Java Comments ?

📄
filename.js
// This is a single-line comment
int x = 10; // This is also a single-line comment

2. Multi-Line Comments #

📄
filename.js
/* This is a multi-line comment
   It can span multiple lines */
int y = 20;

/* Multi-line comments can also be used
   to comment out blocks of code
int z = 30;
*/

📄
filename.js
/**
 * This is a documentation comment
 * It provides information about the class, method, or field
 * 
 * @param args the command line arguments
 */
public class MyClass {
    /**
     * This method performs addition
     * 
     * @param a the first number
     * @param b the second number
     * @return the sum of a and b
     */
    public int add(int a, int b) {
        return a + b;
    }
}

Summary #

  • Single-Line Comments (//): Used for short explanations or annotations.
  • Multi-Line Comments (/* … */): Used for longer explanations or to comment out blocks of code.
  • Documentation Comments (/** … */): Used for generating external documentation with Javadoc.

Why to use Comments?

1. Improving Code Readability #

📄
filename.js
// Calculate the area of a circle
double area = Math.PI * radius * radius;

📄
filename.js
/**
 * Calculates the area of a rectangle.
 *
 * @param length the length of the rectangle
 * @param width the width of the rectangle
 * @return the area of the rectangle
 */
public double calculateArea(double length, double width) {
    return length * width;
}

3. Explaining Complex Logic #

📄
filename.js
// Using the Euclidean algorithm to find the greatest common divisor (GCD)
while (b != 0) {
    int temp = b;
    b = a % b;
    a = temp;
}

4. Marking To-Do Items #

📄
filename.js
// TODO: Handle edge cases for negative inputs
public int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

5. Disabling Code #

📄
filename.js
// System.out.println("Debug: Value of x is " + x);

6. Providing Legal or License Information #

📄
filename.js
/*
 * This software is licensed under the MIT License.
 * See the LICENSE file for more details.
 */

Summary #