Java Comments

Java Comments

Comments in Java are notes written inside the code to explain what the program or a particular line does. Comments make code more readable and help programmers understand logic easily — especially when coming back to code later.

👉 Comments are ignored by the Java compiler and do not affect the program output.


✔ Types of Comments in Java

Java supports three types of comments:

Type Format Usage
Single-line comment // comment Short explanations
Multi-line comment /* comment */ Longer explanations or block comments
Documentation (JavaDoc) comment /** comment */ Generate API documentation


1️⃣ Single-Line Comment

Used to comment one line or short notes.

// This prints a message to the screen
System.out.println("Hello Java!");

Example:

int age = 21; // variable storing age

2️⃣ Multi-Line Comment

Used when explanation spans multiple lines.

/*
This program prints Hello World.
You can add detailed descriptions here.
*/

System.out.println("Hello World");

3️⃣ Documentation Comment (JavaDoc)

Used to describe classes, methods, and generate HTML documentation using the javadoc tool.

/**
* This class prints a greeting message
*/

class Hello {
/**
* This method prints welcome message
*/

public static void main(String[] args) {
System.out.println("Welcome!");
}
}

🧠 Why Use Comments?

  • To explain logic

  • To describe functions or variables

  • For debugging (temporarily disable code)

  • To help other developers understand code


📌 Commenting Out Code (Debugging)

You can disable code temporarily using comments:

System.out.println("Line is active");
// System.out.println("This line is disabled");

❌ Wrong Usage Example

⚠️ You cannot put a comment in the middle of a statement:

System.out. // wrong
println("Hello");

✔ Correct Usage

// Printing message
System.out.println("Hello");

🧪 Example Program With All Comments

/**
* Demo of Java comments
*/

class CommentsDemo {

public static void main(String[] args) {

// Single-line comment
int num = 10;

/*
Multi-line comment
explaining the next line
*/

System.out.println("Number is: " + num);
}
}


⭐ Summary

Comment Type Symbol Purpose
Single-line // Small notes
Multi-line /* ... */ Large explanation or block
JavaDoc /** ... */ Generate documentation

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *