Comments are parts of the code that are completely ignored by the Java compiler. Their purpose is to be read by humans to make the code more understandable.
Good commenting is a crucial practice for professional developers. It helps you and others understand your code, especially when you return to it after a long time.
Java supports three types of comments.
A single-line comment starts with two forward slashes //. The compiler ignores everything from // to the end of the line.
They are useful for short, quick explanations of a single line of code.
public class Main {
public static void main(String[] args) {
// This is a single-line comment. It will not be executed.
System.out.println("This line will be printed.");
int score = 100; // This is an inline comment explaining the variable.
System.out.println(score);
}
}
A multi-line comment starts with /* and ends with */. The compiler ignores everything between these markers.
They are perfect for longer explanations that span multiple lines or for temporarily disabling a whole block of code during testing.
/* This is a multi-line comment. It can span across several lines. The following code calculates a simple sum. */ int x = 10; int y = 20; System.out.println(x + y);
A documentation comment starts with /** and ends with */. These are special comments that can be processed by the Javadoc tool to automatically generate HTML documentation for your code.
They are used to describe classes, methods, and variables. They often include special tags like @param (to describe a method parameter), @return (to describe the return value), and @author.
/**
* The Calculator class provides methods to perform basic arithmetic operations.
*/
class Calculator {
/**
* This method takes two integers and returns their sum.
* @param numA This is the first number.
* @param numB This is the second number.
* @return int The sum of numA and numB.
*/
public int add(int numA, int numB) {
return numA + numB;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(10, 5));
}
}
Using Javadoc comments is a professional standard for creating maintainable and well-documented libraries and applications.