Java Comments

Adding notes and documentation to your Java code

💬 What are Java Comments?

Java comments are text notes in your code that are ignored by the compiler. They help explain what your code does, making it easier to understand and maintain for yourself and others.


// This is a single-line comment
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); // Print greeting
    }
}
                                    

Output:

Hello, World!

Types of Java Comments

💭

Single-line Comments

Use // for one line comments

// This is a single-line comment
int age = 25; // Variable to store age
📝

Multi-line Comments

Use /* */ for multiple lines

/* This is a multi-line comment
   It can span multiple lines
   Very useful for longer explanations */
📚

Documentation Comments

Use /** */ for documentation

/**
 * This method calculates the sum
 * @param a first number
 * @param b second number
 * @return sum of a and b
 */
🚫

Commenting Out Code

Temporarily disable code

System.out.println("This runs");
// System.out.println("This doesn't run");

🔹 Single-line Comments

Single-line comments start with // and continue to the end of the line:

public class CommentExample {
    public static void main(String[] args) {
        // This is a comment explaining the next line
        System.out.println("Learning Java!"); 
        
        int number = 42; // Store a number
        // int unused = 0; // This line is commented out
    }
}

Output:

Learning Java!

🔹 Multi-line Comments

Multi-line comments start with /* and end with */:

public class MultiLineExample {
    public static void main(String[] args) {
        /* 
         * This is a multi-line comment
         * It can explain complex logic
         * or provide detailed information
         */
        System.out.println("Multi-line comments are useful!");
        
        /* You can also use them inline */ int x = 10;
    }
}

Output:

Multi-line comments are useful!

🔹 Best Practices for Comments

Follow these guidelines for effective commenting:

✅ Good Comment Practices:

  • Explain WHY, not WHAT: Focus on the purpose
  • Keep comments updated: Change them when code changes
  • Be clear and concise: Use simple language
  • Comment complex logic: Help others understand
public class BestPractices {
    public static void main(String[] args) {
        // Calculate discount for bulk orders (good - explains why)
        double discount = quantity > 100 ? 0.15 : 0.05;
        
        // NOT: Set discount to 0.15 (bad - explains what, not why)
        
        // TODO: Add validation for negative quantities
        System.out.println("Discount: " + discount);
    }
}

🧠 Test Your Knowledge

Which symbol starts a single-line comment in Java?