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,
- / * This is a multi-line comment.
- * The problem prints “Hello, World!” to the standard output.
- * /
- class HelloWorld {
- public static void main (String [] args) {
- {
- System.out.println (“Hello, World!”);
- }
- }
- }
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,
- // “Hello, World!” program
- class AssignmentOperator {
- public static void main (String [] args) {
- {
- System.out.println (“Hello, World!”); // prints “Hello, World!”
- }
- }
- }
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.”