You will learn about Java comments in this course, including their purpose and their usage.
In computer programming, comments are a part of the code that Java compilers entirely disregard. They are mostly employed to aid programmers in comprehending 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,
- Identify and set up two variables
- print the results
Types of Comments in Java
In Java, there are two types of comments:
- single-line comment
- multi-line comment
Single-line Comment
A comment that is one line long begins and ends on that same line. The / symbol can be utilized to create a single-line comment. 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!”
Everything from/to the end of the line is ignored by the Java compiler. Thus, it is also known as a comment at the end of a line.
Multi-line Comment
The multi-line comment can be used to write remarks across multiple lines. The /…./ sign can be used to create comments that span multiple lines. 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.
*/
Traditional Comment is another name for this kind of remark. The Java compiler ignores everything from /* to */ in this kind of comment.
Use Comments the Right Way
One thing you should always keep in mind is that comments shouldn’t serve as a substitute for an English language explanation of badly written code. Always develop self-explanatory code that is nicely organized. Afterward, utilize the comments.
Some people think that code should be self-explanatory and that comments should be utilized sparingly. However, in my opinion, making remarks is perfectly acceptable. Comments can be used to describe complex algorithms, regex, or situations where we must select one strategy from a variety of options in order to solve difficulties.