Comments are non-executable statements used to explain the purpose of the code. They are completely ignored by the Java compiler but are vital for human developers who maintain the software.
Imagine reading 5,000 lines of code written two years ago without a single note. It would be a nightmare! Comments serve four main purposes:
The most common type of comment is the single-line comment. It starts with two forward slashes //. Any text between // and the end of the line is ignored by Java.
Developers usually use single-line comments for quick notes or to explain a specific variable's purpose.
If your explanation is long and requires multiple lines, you can use multi-line comments. These start with /* and end with */.
Note: You cannot nest multi-line comments. Putting a /* */ inside another /* */ will cause a compilation error.
This is a unique feature of Java. Documentation comments start with /** and end with */. They are used to create **API Documentation** that can be read by tools to generate HTML pages (like the official Oracle Java Docs).
| Tag | Description |
|---|---|
@author |
Identifies the developer who wrote the code. |
@param |
Explains the input parameters of a method. |
@return |
Explains what value the method sends back. |
@version |
Specifies the current version of the software. |
One of the most practical uses for comments is "commenting out" code. If your program has an error, you can disable parts of it to isolate the problem.
int a = 10; // set a to 10 (Obvious comments are a waste of space).
int a = 10; // Initial threshold for the sensor (Explains the meaning of the value).
Commenting is an art that makes you a professional developer. Now that you know how to document your logic, let's learn how to store and manipulate data. In the next chapter, we dive into Java Variables.
Next: Java Variables →