Java Comments | About, Types and Examples

Java Comments | About, Types and Examples

6 mins read38 Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 12, 2024 16:24 IST

Do you know what makes the code more readable? Comments, as they provide valuable context and explanations about the code, making it easier for both the original developers and others who work with the code to understand its purpose and functionality. In this blog, let us deep dive on comments used in Java programming language!

Java comments are notes in the source code of a Java program that are ignored by the compiler. They are used to provide explanations, descriptions, or any relevant information about the code. It makes it easier to understand for humans.

Table of Content

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
– / –
170 hours
β‚Ή5.4 K
1 month
– / –
2 months
– / –
6 months
β‚Ή5.5 K
1 month
β‚Ή17 K
3 months

Why Do We Use Java Comments?

We use Java comments because of the following

  1. They help explain complex logic.
  2. Useful for generating documentation and guiding future developers.
  3. Enable temporarily disabling code sections for testing and debugging purposes.

For example, 


 
// Print a greeting message to the console
System.out.println("Hello World");
Copy code

Types of Java Comments

We have three types of comments in Java

  • Single-Line Comments
  • Multi-Line Comments
  • Documentation Comments

Let’s understand each one by one in detail

Single-Line Comments

Single-line comments in Java are used to comment out a single line or a part of it. They begin with two forward slashes (//) and extend to the end of the line. Single-line comments are helpful for brief explanations or notes relevant to the local code. 

Syntax

// comment text

Example

In the code below, single-line comments describe each step in the program, making the code more readable and understandable.


 
public class Main {
public static void main(String[] args) {
// Declare a variable to store the number
int number = 10;
// Calculate the square of the number
int square = number * number;
// Print the result
System.out.println("The square of " + number + " is: " + square);
}
}
Copy code

Output

The square of 10 is: 100
 

Multi-Line Comments

Multi-line comments in Java are used to comment out blocks of text spanning multiple lines. They start with /* and end with */. Everything between these markers is considered a comment and is ignored by the Java compiler. Multi-line comments help provide detailed explanations or temporarily disable a block of code during debugging.

Syntax

/* 
  This is a multi-line comment.
  It can span several lines.
  The Java compiler ignores everything in this block.
*/

Example

In the code below, the multi-line comment provides a clear explanation of the Fibonacci sequence and the logic behind the loop that calculates it. This kind of detailed explanation helps in understanding the purpose and functionality of the code, especially for complex algorithms.


 
public class Main {
public static void main(String[] args) {
int n = 10; // number of elements in the Fibonacci series
/* The Fibonacci sequence is a series of numbers where
a number is the addition of the last two numbers,
starting with 0, and 1.
This loop calculates each number in the series
up to the nth number and prints them. */
int n1 = 0, n2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i) {
System.out.print(n1);
if (i < n) {
System.out.print(", ");
}
// compute the next term
int sum = n1 + n2;
n1 = n2;
n2 = sum;
}
}
}
Copy code

Output

First 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Constructors in Java Explained
How to Return an Array in Java
Polymorphism in Java: Meaning and its Types

Documentation Comments

Documentation comments in Java, often referred to as doc comments, are a special type of comment used to generate JavaDoc documentation. JavaDoc is a tool provided by Oracle that generates standard HTML documentation from these comments. Documentation comments are crucial for explaining the code’s functionality, parameters, return values, and thrown exceptions at a higher level. It makes them an essential part of professional Java development.

Syntax

/**
 * Description or summary of the class, method, or field.
 *
 * @tag description
 */

Important components of this syntax include

  • Start and End: The comment begins with /** and ends with */. This distinguishes it from regular multi-line comments that start with /*.
  • Description: The first part is usually a description or summary of the class, method, or field that the comment is documenting.
  • Tags: After the description, you can include various tags to provide more specific information.

 Various tags used in Java documentation comments are as follows.

Tag Name Description Syntax Example
@param Describes a parameter passed to a method or constructor. @param paramName description
@return Describes the return value of methods. @return description
@throws/@exception Describes the exception thrown by a method. @throws ExceptionClass description
@see Adds a reference or a link to another element. @see className#methodName
@author States the author of the code. @author name
@version Specifies the version of the class, interface, or method. @version versionInfo
@since Indicates when the class, method, or field was first added to the project. @since version
@deprecated Marks the method or class as obsolete. @deprecated description
@link Inserts an inline link to another element in the documentation. {@link package.class#member label}
@linkplain Like @link, but displays the link text instead of the code font. {@linkplain package.class#member label}
@code Displays text in code font. {@code code}
@literal Indicates that text should be interpreted literally, ignoring Javadoc tags. {@literal text}

Example

In the code below, documentation comments are used. This type of commenting is essential for large-scale projects, API libraries, or any Java code that will be used or maintained by others, as it ensures that anyone reading the code can quickly understand its purpose, usage, and behaviour without delving into the implementation details.


 
/**
* The BankAccount class simulates a bank account.
*/
public class BankAccount {
/**
* The balance field stores the current balance.
*/
private double balance;
/**
* The constructor initializes the balance to 0.
*/
public BankAccount() {
balance = 0;
}
/**
* The deposit method adds money to the account.
*
* @param amount The amount to add to the balance.
*/
public void deposit(double amount) {
balance += amount;
}
/**
* The withdraw method subtracts money from the account.
*
* @param amount The amount to subtract from the balance.
*/
public void withdraw(double amount) {
balance -= amount;
}
/**
* The getBalance method returns the account balance.
*
* @return The current balance of the account.
*/
public double getBalance() {
return balance;
}
/**
* The main method for the BankAccount class.
*
* @param args Command line arguments (not used).
*/
public static void main(String[] args) {
BankAccount myAccount = new BankAccount();
// Demonstrate deposit
myAccount.deposit(200.00);
System.out.println("Balance after deposit: " + myAccount.getBalance());
// Demonstrate withdrawal
myAccount.withdraw(50.00);
System.out.println("Balance after withdrawal: " + myAccount.getBalance());
}
}
Copy code

Output

Balance after deposit: 200.0
Balance after withdrawal: 150.0

Best Practices While Using Java Comments

  • Keep comments concise and relevant to the code they describe.
  • Use comments to explain complex logic or provide context when necessary.
  • Update comments when code changes to ensure accuracy.
  • Use meaningful variable and method names to minimize the need for excessive comments.

Understanding If Condition in Java

Star Pattern Programs in Java

What are Identifiers in Java?

Array Programs in Java | Beginner to Expert Level

Understanding Variables in Java

Number Pattern Programs in Java

Key Takeaways

  • Java comments make the source code more readable and understandable.
  • Java supports three main types of comments – Single-Line Comments for brief notes, Multi-Line Comments for detailed explanations or disabling code, and Documentation Comments for generating JavaDoc.
  • Comments in Java are ignored by the compiler, meaning they don’t affect the execution of the code but serve as a guide or documentation for developers.

FAQs

What are Comments in Java?

Comments in Java are statements that are not executed by the compiler and interpreter. They are used to provide information or explanations about the code, making it easier to understand for humans. Comments are useful for documentation and for explaining complex parts of the code.

What are the Types of Comments in Java?

Java supports three types of comments:

  • Single-Line Comments: Start with // and extend to the end of the line.
  • Multi-Line Comments: Start with /* and end with */. They can span multiple lines.
  • Documentation Comments: Start with /** and end with */. These are used to create formal documentation using Javadoc.

How Do You Write a Single-Line Comment in Java?

Single-line comment in Java is written by starting the line with two forward slashes (//). Everything on the right of // on the same line is treated as a comment. For example: // This is a single-line comment.

Can Comments be Nested in Java?

In Java, single-line and multi-line comments cannot be nested within each other. Attempting to nest comments will lead to a compilation error. However, you can have single-line comments inside multi-line comments or vice versa, as long as they are not trying to nest within each other.

What is the Purpose of Documentation Comments in Java?

Documentation comments (or Javadoc comments) in Java are used to write documentation for Java code. They are processed by the Javadoc tool to generate formal documentation in HTML format.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio