Skip to content

Java Comments

Java comments - those little notes that make a big difference in our code readability and understanding.

Java comments are like your personal annotations in the margins of your code, helping you and others understand what's going on. They provide valuable context, explanations, and reminders, making your code easier to read, maintain, and debug.

Types of Java Comments

Java offers three main types of comments, each serving a unique purpose and adding value to your code. Let's explore them one by one:

Single-Line Comment

Single-line comments are perfect for adding quick annotations or explanations to specific lines of code. They start with two forward slashes (//) and continue until the end of the line. Single-line comments are great for adding context, clarifying intentions, or temporarily disabling code.

Example

java
int num1 = 10; // Initialize num1 to 10
int num2 = 20; // Initialize num2 to 20
int sum = num1 + num2; // Calculate the sum of num1 and num2
System.out.println("Sum: " + sum); // Print the sum

Multi-Line Comment

Multi-line comments are ideal for adding longer explanations or descriptions that span multiple lines of code. They start with /* and end with */, allowing you to write detailed comments without interruption. Multi-line comments are useful for documenting the purpose of classes, methods, or complex algorithms.

Example

java
/*
This method calculates the factorial of a given number.
It takes an integer input and returns its factorial.
*/
public static int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1; // Base case: factorial of 0 or 1 is 1
    } else {
        return n * factorial(n - 1); // Recursive case: multiply n with factorial of (n-1)
    }
}

Documentation Comment

Documentation comments, also known as Javadoc comments, are a special type of comment used for generating documentation automatically. They start with / and end with */, and are typically used to document classes, methods, and fields. Documentation comments follow a specific format and can include tags like @param, @return, and @throws to provide additional information.

Example

java
/**
 * This class represents a simple calculator.
 * It provides methods for performing basic arithmetic operations.
 */
public class Calculator {
    
    /**
     * Adds two integers and returns the result.
     * @param num1 The first integer to be added.
     * @param num2 The second integer to be added.
     * @return The sum of num1 and num2.
     */
    public static int add(int num1, int num2) {
        return num1 + num2;
    }
}

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.