Java Comments
Inside a Java program, you can write special text known as a comment, which will be ignored by the Java compiler. The compiler checks the code for syntax and logic, but comments are excluded from this process. Comments allow you to exclude code from the compilation process – which is equivalent to disabling it, or clarify a piece of code to yourself or others. They can serve as a guide for developers to understand the logic behind your code. In our materials, we use comments in the theory and practice lessons to explain how and why our code works.
The Java programming language supports three kinds of comments.
Single-line comments
The Java compiler ignores any text from //
to the end of that line.
1class Program {
2 public static void main(String[] args) {
3 // The line below will be ignored
4 // System.out.println("Hello, World");
5 // It prints the string "Hello, Java"
6 System.out.println("Hello, Java"); // Here can be any comment
7 }
8}
In the example above, the text after //
is ignored by the compiler. Single-line comments are also called End-of-line comments.
Multi-line comments
The compiler ignores any text from /*
to the nearest */
. It can be used for multiple and single line comments.
1class Program {
2 public static void main(String[] args) {
3 /* This is a single-line comment */
4 /* This is an example of
5 a multi-line comment */
6 }
7}
You can nest end-of-line comments inside multi-line comments, like in this code block:
1class Program {
2 public static void main(String[] args) {
3 /*
4 System.out.println("Hello"); // print "Hello"
5 System.out.println("Java"); // print "Java"
6 */
7 }
8}
Most of the code above is ignored by the compiler because of the /* ... */
characters.
Java documentation comments
Java documentation comments looks a bit different than multi-line comments. It starts with /**
and ends with */
. The compiler ignores any text between /**
and */
just like it ignores multi-line comments.
These kinds of comments help you automatically generate documentation about your source code by using the javadoc tool. Usually, these comments are placed above declarations of classes, interfaces, methods and so on as those are the main focus of documentation. Some special types of comments with labels such as @param
or @return
are often used for controlling the tool. However, they are optional and we will not deal with them for now. Just don't be surprised in case you see them.
The following example showcases documentation comments:
1class Program {
2 /**
3 * The main method accepts an array of string arguments
4 *
5 * @param args from the command line
6 */
7 public static void main(String[] args) {
8 // do nothing
9 }
10}