Comments in Java:
A comment is an explanation or description of the source code of the program. It helps a developer explain the logic of the code and improves program readability. They are generally ignored by compilers and interpreters.
Why do we need comments?
The code tells you what is being done and how, but it doesn’t tell you why it has been done. Take an example where you have initialized a variable of a data type. But someone seeing your code the first time might not know why you have initialized it.
Comments are important so that the person maintaining the program will be able to tell exactly what each section of the code does. Sometimes the programmer maintaining the source code might even forget what the line of code does in a whole program after a year of completion of the project.
Types of Comments in Java:
There are two types of comments in Java;
- Single-line comment.
- Multi-line comment.
Single Line comment:
A single-line comment starts and ends in the same line. To write a single-line comment, we can use the // symbol. It is applicable for a single line only. Compliers ignore the line which has been commented.
Syntax:
// Single Line comment
Code:
Java Code
class Main {
public static void main(String args[]) {
// The programs print Takeuforward string
System.out.println("Takeuforward");
}
}
Single Line comment at the end of line
Code:
Java Code
class Main {
public static void main(String args[]) {
System.out.println("Takeuforward"); // The programs print Takeuforward string
}
}
Multi-Line comment:
When we have to write comments in multiple lines, we can use the multi-line comment. Multi-line comment starts with forwarding slash / and asterisk (/*), and ends with asterisk and forward-slash (*/).
Syntax:
/* Comment starts Multi line comment Continues */ Comment ends
Code:
Java Code
class Main {
public static void main(String args[]) {
/* Multi line comments
are used to write documentation
or instructions in a brief*/
System.out.println("Takeuforward");
}
}
Special thanks to Rushikesh Aadav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article