Start learning free

LESSON 3 OF 410 · WELCOME TO JAVA

Comments in Java

Lesson Read the full explanation

TL ; DR:

  • Comments are lines of code that Java will intentionally ignore (not execute). They don't do anything.


  • You add a single line comment in Java by typing // followed by any text:

    // This is a comment!
    System.out.println("This is not!");
    


Full lesson:

Comments are lines of code that Java will intentionally ignore. They don't do anything.

They're just used to create notes for yourself and others about what the code does.

There are two types of code comments in Java:


1. Single line comments:

We create single line comments by typing // and Java will ignore (not execute) any text between // and the end of the line.

Single line comments automatically end at the next line of code:

// Next line will greet the user:
System.out.println("Hello user!");

Output of this code:

Hello user!

We can also use single line comments at the end of a line to explain the code:

System.out.println("Hello user!"); // This line greets the user
System.out.println("This is not a comment!");

Output of this code:

Hello user!
This is not a comment!

2. Multi-line comments

We can also comment multiple lines of code using multi-line comments.

We type /* to begin the comment and type */ to end the comment:

/* This is a 
multi-line comment
System.out.println("This will not run");
Next line will greet the user:
*/

System.out.println("Hello user!");

Output of this code:

Hello user!

Assignment
Follow the Coding Tutorial and let's write some comments!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · WELCOME TO JAVA

    Comments in Java, explained

    Introduction

    In this lesson, we will explore the concept of comments in Java. Comments are an essential part of programming as they help developers understand the code better. They are especially useful for documenting the purpose of code blocks, explaining complex logic, and leaving notes for future reference. Comments are ignored by the Java compiler, meaning they do not affect the execution of the program.

    Understanding the Basics

    Comments in Java come in two main types: single-line comments and multi-line comments. Understanding these basics is crucial as they form the foundation for writing clear and maintainable code.

    Single-Line Comments

    Single-line comments start with // and extend to the end of the line. They are useful for brief explanations or notes.

    // This is a single-line comment
    System.out.println("Hello, World!"); // This prints a message to the console
    

    Multi-Line Comments

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

    /* This is a multi-line comment
       It can span multiple lines
       System.out.println("This will not run");
    */
    System.out.println("Hello, World!");
    

    Main Concepts

    Comments are primarily used for documentation and explanation. They help make the code more readable and maintainable. Here are some key concepts and techniques:

    Documentation

    Comments can be used to document the purpose of a class, method, or variable. This is especially useful in large projects where multiple developers are involved.

    // This class represents a simple calculator
    public class Calculator {
        // This method adds two numbers
        public int add(int a, int b) {
            return a + b;
        }
    }
    

    Explanation

    Comments can explain complex logic or algorithms, making it easier for others (or yourself) to understand the code later.

    public int factorial(int n) {
        // Base case: factorial of 0 is 1
        if (n == 0) {
            return 1;
        }
        // Recursive case: n * factorial of (n-1)
        return n * factorial(n - 1);
    }
    

    Examples and Use Cases

    Let's look at some examples and use cases where comments are beneficial:

    Example 1: Simple Program

    // This program prints a greeting message
    public class Greeting {
        public static void main(String[] args) {
            // Print greeting message to the console
            System.out.println("Hello, user!");
        }
    }
    

    Example 2: Complex Logic

    public class Fibonacci {
        // This method calculates the nth Fibonacci number
        public int fibonacci(int n) {
            // Base cases
            if (n == 0) return 0;
            if (n == 1) return 1;
            // Recursive case
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }
    

    Common Pitfalls and Best Practices

    While comments are helpful, there are some common pitfalls to avoid and best practices to follow:

    Common Pitfalls

    • Over-commenting: Adding too many comments can clutter the code and make it harder to read.
    • Outdated comments: Comments that do not match the code can be misleading.

    Best Practices

    • Keep comments concise: Write clear and concise comments that add value.
    • Update comments: Ensure comments are updated when the code changes.
    • Use comments for explanation: Use comments to explain why something is done, not what is done.

    Advanced Techniques

    As you become more experienced, you may encounter advanced commenting techniques such as Javadoc comments. Javadoc comments are used to generate documentation for your code and are written using a specific syntax.

    /**
     * This class represents a simple calculator.
     */
    public class Calculator {
        /**
         * Adds two numbers.
         * @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;
        }
    }
    

    Code Implementation

    Here is a well-commented code snippet demonstrating the use of comments in a real-world scenario:

    public class ShoppingCart {
        // List to store items in the cart
        private List<String> items;
    
        // Constructor to initialize the cart
        public ShoppingCart() {
            items = new ArrayList<>();
        }
    
        // Method to add an item to the cart
        public void addItem(String item) {
            items.add(item);
        }
    
        // Method to remove an item from the cart
        public void removeItem(String item) {
            items.remove(item);
        }
    
        // Method to display items in the cart
        public void displayItems() {
            System.out.println("Items in the cart:");
            for (String item : items) {
                System.out.println(item);
            }
        }
    
        public static void main(String[] args) {
            // Create a new shopping cart
            ShoppingCart cart = new ShoppingCart();
            // Add items to the cart
            cart.addItem("Apple");
            cart.addItem("Banana");
            // Display items in the cart
            cart.displayItems();
            // Remove an item from the cart
            cart.removeItem("Apple");
            // Display items in the cart again
            cart.displayItems();
        }
    }
    

    Debugging and Testing

    Comments can also be useful for debugging and testing. Here are some tips:

    Debugging

    • Comment out code: Temporarily comment out code to isolate issues.
    • Add debug comments: Use comments to mark sections of code for debugging.

    Testing

    • Document test cases: Use comments to explain the purpose of test cases.
    • Mark known issues: Comment on known issues or bugs for future reference.

    Thinking and Problem-Solving Tips

    When approaching problems related to comments, consider the following strategies:

    • Break down complex problems: Use comments to break down complex problems into manageable parts.
    • Practice writing comments: Regularly practice writing comments to improve clarity and readability.
    • Review and refactor: Periodically review and refactor comments to ensure they remain relevant and helpful.

    Conclusion

    In this lesson, we covered the importance of comments in Java, the different types of comments, and best practices for using them. Comments are a powerful tool for making your code more understandable and maintainable. By mastering the use of comments, you can improve the quality of your code and make it easier for others to work with.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free