Java Docs
Java Documentation
Java Comments
In the previous tutorial, you learned to write your first Java program. Now, let's learn about Java comments.
Comments are hints added to code to make it easier to read and understand. They are completely ignored by the Java compiler.
Example
class HelloWorld {
public static void main(String[] args) {
// print Hello World to the screen
System.out.println("Hello World");
}
}Output
Hello World
Here, // print Hello World to the screen is a comment. Anything after // is ignored.
Single-line Comment
A single-line comment begins with // and ends at the end of the line.
// declare and initialize two variables
int a = 1;
int b = 3;
// print the output
System.out.println("This is output");The Java compiler ignores everything from // to the end of the line.
Multi-line Comment
Use /* ... */ to write comments across multiple lines.
/* 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!
The compiler ignores everything from /* to */.
Prevent Executing Code Using Comments
Comments are useful for temporarily disabling code while debugging.
public class Main {
public static void main(String[] args) {
System.out.println("some code");
System.out.println("error code");
System.out.println("some other code");
}
}If the middle line causes an error, you can disable it:
public class Main {
public static void main(String[] args) {
System.out.println("some code");
// System.out.println("error code");
System.out.println("some other code");
}
}Why Use Comments?
- To make the code readable for future reference.
- Helpful during debugging.
- Useful for team collaboration and code understanding.
Comments should not replace clean code. Prefer explaining why something is done rather than how.
Next, we will learn about Java variables and literals.