In Java, comments are non-executable statements that explain code and improve readability. They are ignored by the compiler and do not affect program execution.
- Enhance code readability and maintainability.
- Useful for debugging and documenting logic.
Java supports three main types of comments:
Single-line comments are used to comment on one line of code.
Syntax:
// Comments here( Text in this line only is considered as comment )
Java
// Java program to show single line comments
class GFG
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single Line Comment Above");
}
}
OutputSingle Line Comment Above
Multi-line comments are used to describe complex code or methods, as writing multiple single-line comments can be tedious.
/*
Comment starts
continues
continues...
Comment ends
*/
Java
class GFG
{
public static void main(String args[])
{
System.out.println("Multi Line Comments Below");
/* Comment line 1
Comment line 2
Comment line 3
*/
}
}
OutputMulti Line Comments Below
Documentation comments are used to generate external documentation using Javadoc. They are generally used in professional projects to describe classes, methods, and parameters.
Syntax:
/**
* Comment start
* @param param-name description
* @return description
*/
Java
/**
* <h1>Find Average of Three Numbers</h1>
* Calculates the average of three integers.
* @author Pratik Agarwal
* @version 1.0
* @since 2017-02-18
*/
public class FindAvg{
/**
* Finds average of three integers.
* @param numA First parameter
* @param numB Second parameter
* @param numC Third parameter
* @return Average of numA, numB, and numC
*/
public int findAvg(int numA, int numB, int numC)
{
return (numA + numB + numC) / 3;
}
/**
* Main method which uses findAvg method
* @param args Unused
*/
public static void main(String args[]){
FindAvg obj = new FindAvg();
int avg = obj.findAvg(10, 20, 30);
System.out.println("Average of 10, 20, and 30 is: "
+ avg);
}
}
OutputAverage of 10, 20, and 30 is: 20
Related Article: JavaDoc tool
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java