Site icon DED9

Learning Comments In Java (In Quite Simple Language)

In this tutorial, you will learn about comments in Java and why and how to use them.

In programming, comments are considered part of the program that is used to understand the code and is completely ignored and not executed by Java compilers.

So In the Java programming language, there are two types of comments:

Common comment /*…….*/

This is a multi-line comment that can be multiple lines. The Java compiler ignores everything from / * to * /. For example,

  1. / * This is a multi-line comment.
  2. * The problem prints “Hello, World!” to the standard output.
  3. * /
  4. class HelloWorld {
  5. public static void main (String [] args) {
  6. {
  7. System.out.println (“Hello, World!”);
  8. }
  9. }
  10. }

In the above code, the comment is equal to:

/ * This is a multi-line comment.

* The problem prints “Hello, World!” to the standard output.

* /

One line comment //

The compiler ignores everything from // to the bottom of the line. For example,

  1. // “Hello, World!” program
  2. class AssignmentOperator {
  3. public static void main (String [] args) {
  4. {
  5. System.out.println (“Hello, World!”); // prints “Hello, World!”
  6. }
  7. }
  8. }

The above program includes two one-line comments:

// “Hello, World!” program

And

// prints “Hello, World!”

Use the comments in the right way

Comments should not be a substitute for explaining poorly written code in English. Write code with good structure and readability and use comments.

Some believe that the code should be documented and the comments should be few. However, we are completely against it (this is our personal opinion). There is no problem in using comments to explain complex algorithms, regex or scenarios.

Use comments to explain “why” instead of “how.”

Exit mobile version