In this article, you will learn-
Java Comments
In this tutorial, you will find out about Java comments, why we use them, and how to use comments in the right way.
In computer programming, comments are a segment of the program that is totally disregarded by Java compilers. They are essentially used to assist programmers to understand the code. For instance,
// declare and initialize two variables
int a =1;
int b = 3;
// print the output
System.out.println("This is output");
Here, we have used the following comments,
declare and initialize two variables
print the output
Types of Comments in Java
In Java, there are two types of comments:
single-line comment
multi-line comment
Single-line Comment
A single-line comment starts and finishes in a similar line. To write a single-line comment, we can use the //symbol. For instance,
// "Hello, World!" program example
class Main {
public static void main(String[] args) {
{
// prints "Hello, World!"
System.out.println("Hello, World!");
}
}
Output
Hello, World!
Here, we have used two single-line comments:
"Hello, World!" program example
prints "Hello World!"
The Java compiler ignores everything from // to the end of the line. Hence, it is also known as End of Line comment.
Multi-line Comment
At the point when we need to write comments in various lines, we can use the multi-line comment. To write multi-line comments, we can use the/…./symbol. For instance,
/* This is an example of multi-line comment.
* The program prints "Hello, World!" to the standard output.
*/
class HelloWorld {
public static void main(String[] args) {
{
System.out.println("Hello, World!");
}
}
Output
Hello, World!
Here, we have used the multi-line comment:
/* This is an example of multi-line comment.
* The program prints "Hello, World!" to the standard output.
*/
This type of comment is otherwise called Traditional Comment. In this type of comment, the Java compiler overlooks everything from/* to */.
Use Comments the Right Way
One thing you ought to consistently consider that comments shouldn’t be the substitute for an approach to clarify inadequately written code in English. You ought to consistently compose very much organized and self clarifying code. What’s more, at that point use comments.
Some believe that code should be self-describing and comments should be rarely used. However, there is nothing wrong with using comments. We can use comments to clarify complex algorithms, regex, or situations where we need to pick one procedure among the various methods to tackle issues.
Note: In many cases, consistently use comments to clarify ‘why‘ instead of ‘how‘ and you are good to go.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.