Code comments in Java are useful because they allow us to add notes to explain code and make it more readable. Commenting is also possible to control the execution of some code segments and test new lines that allow us to solve a problem without deleting what was previously.
There are two types of comments:
- A single line comments
- Multiline comments
Single line comments
Single line comments begin with two forward slashes //.
Text between double slashes and a newline will be ignored by the compiler. Here is an example:
//This is a one line comment System.out.println("This code if compiled and run");
Another valid form of a comment is after a code statement and before the line break:
System.out.println("Hello"); //This comment is also valid
Multiline comments
Multi-line comments begin with a slash followed by an asterisk and end with an asterisk followed by a slash. Any text between /* and */ will be ignored by the Java compiler.
Here is an example:
package com.geekole; // Name of your java package public class Example { public static void main(String args[]) { /* This text is a multiline comment, it can span one or more lines. */ System.out.println("Hello World"); } }
It is possible to comment code just to try something new:
package com.geekole; // Name of your java package public class Example { public static void main(String args[]) { /* System.out.println("Hello World"); */ System.out.println("Hello World"); } }
It is also common to add code comments at the beginning of each method to describe its operation a bit and make it more readable in Java.