HOME HTML EDITOR C JAVA PHP

Java Comments: Writing Readable Code

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.

The Developer's Rule: "Code is read much more often than it is written." Comments help you communicate with your future self and your teammates.

1. Why are Comments Important?

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:

2. Single-line Comments

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.

// This is a standalone single-line comment int speed = 80; // This is an end-of-line comment System.out.println(speed);

Developers usually use single-line comments for quick notes or to explain a specific variable's purpose.

3. Multi-line Comments

If your explanation is long and requires multiple lines, you can use multi-line comments. These start with /* and end with */.

/* The following block of code calculates the compound interest based on the user's input and the current bank rates. */ double principal = 1000.0; double rate = 5.5;

Note: You cannot nest multi-line comments. Putting a /* */ inside another /* */ will cause a compilation error.

4. Java Documentation Comments (Javadoc)

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).

/** * This method calculates the area of a circle. * @param radius The radius of the circle. * @return The calculated area as a double. */ public double calculateArea(double radius) { return Math.PI * radius * radius; }

Common Javadoc Tags:

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.

5. Using Comments for Debugging

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.

// System.out.println("This line is broken and won't run"); System.out.println("This line is working fine!");

6. Best Practices for Writing Comments

Don't do this:

int a = 10; // set a to 10 (Obvious comments are a waste of space).

Do this:

int a = 10; // Initial threshold for the sensor (Explains the meaning of the value).

Ready to handle data?

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 →