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

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
Constructors in Java Explained
In Java, constructors initialize newly created objects, setting their initial state. They share the same name as the class, lack a return type, and are automatically invoked upon object instantiation.
How to Return an Array in Java
How to Return an Array in Java
In Java, methods can return arrays to provide multiple data elements of a consistent type in a single response. There are various ways on how to return an array. Today...read more
Polymorphism in Java: Meaning and its Types
Polymorphism in Java: Meaning and its Types
Polymorphism is a fancy-sounding word that really just means “many shapes.” And in the world of Java programming, it refers to the ability of objects to take on different forms...read more

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
Understanding If Condition in Java
Have you ever wondered how Java programs make decisions? The if condition in Java is the key. It allows code to branch out based on conditions, thus introducing dynamic decision-making...read more

Star Pattern Programs in Java
Star Pattern Programs in Java
Pattern programs in Java are a type of problem that uses nested loops to produce different patterns of numbers, stars (*), or other characters. In this blog, we will dive...read more

What are Identifiers in Java?
What are Identifiers in Java?
Have you ever wondered how Java keeps everything organized and accessible? It's all because of identifiers. Those unique labels assigned to variables, methods, and classes. These crucial elements of Java...read more

Array Programs in Java | Beginner to Expert Level
Array Programs in Java | Beginner to Expert Level
Array programs in Java traverse from basic single-dimensional arrays to complex multi-dimensional arrays and dynamic arrays using ArrayList. From initializing and accessing array elements, to advanced operations like sorting and...read more

Understanding Variables in Java
Understanding Variables in Java
Have you ever wondered how data is stored and manipulated in Java programs? Variables in Java are the answer, acting as containers for data values. Each variable is defined with...read more

Number Pattern Programs in Java
Number Pattern Programs in Java
Pattern programs in Java are a type of problem that use nested loops to produce different patterns of numbers, stars (*), or other characters. In this blog we will dive...read more

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