Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java Comments: Types, Usage, and Best Practices

Java Comments

This guide explains Java comments, why they matter, and how to use them correctly for clearer, more maintainable code.

In programming, comments are sections of source code that Java compilers ignore. They help developers understand code intent without affecting execution. For example:

// declare and initialize two variables
int a = 1;
int b = 3;

// print the output
System.out.println("This is output");

Here we used two comments: declare and initialize two variables and print the output.


Types of Comments in Java

Java supports two primary comment styles:


Single‑Line Comment

A single‑line comment starts with // and extends to the end of the line. Example:

// "Hello, World!" program example
class Main {
    public static void main(String[] args) {
        // prints "Hello, World!"
        System.out.println("Hello, World!");
    }
}

Output:

Hello, World!

We used two single‑line comments: "Hello, World!" program example and prints "Hello, World!". The compiler ignores everything from // to the line’s end.


Multi‑Line Comment

When you need several lines, use /* … */. Example:

/* This is an example of a 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 skips everything between /* and */. This is also called a traditional comment.


Using Comments Effectively

Comments should not replace clear code. Write well‑structured, self‑describing code first, then add comments to explain the "why" behind decisions—complex algorithms, design choices, or non‑obvious logic.

While some advocate minimal comments, a concise explanation can greatly improve readability for future maintainers.

Note: Prefer comments that explain why a piece of code exists over how it works.


Java

  1. Mastering C# Comments: Types, Best Practices, and XML Documentation
  2. Master Java Operators: Types, Syntax, & Practical Examples
  3. Mastering Java if…else: Control Flow Explained
  4. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  5. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  6. Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
  7. Java Annotations Explained: Types, Placement, and Practical Examples
  8. Mastering Comments in C: Writing Clear, Effective Notes
  9. Java Documentation Comments: Mastering Javadoc and Comment Types
  10. Mastering Comments in C++: Best Practices & Syntax