Java Comments

Comments are notes inside the code. The compiler ignores them. They help other people (and you after six months) to understand the code.

Single line comment

Starts with // and goes to the end of the line.

public class Main {
    public static void main(String[] args) {
        // This line is only a comment
        System.out.println("Hello"); // comment after code
    }
}
Output

Hello

Multi line comment

Starts with /* and ends with */.

public class Multi {
    public static void main(String[] args) {
        /* This is a comment
           on more than one line. */
        System.out.println("Done");
    }
}
Output

Done

Javadoc comment

Starts with /**. The javadoc tool reads these comments and makes HTML documentation. Use them before classes and methods.

public class Doc {
    /**
     * Adds two numbers.
     *
     * @param a the first number
     * @param b the second number
     * @return the sum of a and b
     */
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
    }
}
Output

5

Comment out code

You can put // before a line to stop it from running, without deleting it. This is useful when you test.

public class Off {
    public static void main(String[] args) {
        System.out.println("One");
        // System.out.println("Two");
        System.out.println("Three");
    }
}
Output

One
Three

Good comments

  • Explain why, not what. The code already shows what it does.
  • Keep them short and update them when the code changes.
  • Use clear names for variables and methods, then you need fewer comments.
Note: A wrong comment is worse than no comment. Delete old comments when you change the code. Next: Java Variables.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is the difference between Java and JavaScript?
What is Java?
What are the main features of Java?
What is the difference between JDK, JRE and JVM?
Why is Java platform independent?
What is bytecode in Java?
Why is the main method public static void in Java?