Comments are an essential part of any programming language, including Java. They are used to explain and document code, making it easier to read and maintain. Comments are ignored by the Java compiler, so they do not affect the execution of the program.
Single-line comments start with two forward slashes (//
). Everything following //
on that line is considered a comment and is ignored by the compiler.
// This is a single-line comment
System.out.println("Hello, world!"); // This is an inline comment
Multi-line comments start with /*
and end with */
. Everything between these markers is considered a comment and is ignored by the compiler.
/*
This is a multi-line comment
that spans multiple lines.
*/
System.out.println("Hello, world!");
Documentation comments, also known as Javadoc comments, are used to generate API documentation. These comments start with /**
and end with */
. They can be used to describe classes, methods, and fields.
/**
* The Main class implements an application that
* simply prints "Hello, world!" to the standard output.
*/
public class Main {
/**
* This is the main method which makes use of the println method.
* @param args Unused.
*/
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Javadoc comments can include special tags that provide additional information. Some commonly used Javadoc tags include:
@param
: Describes a method parameter.@return
: Describes the return value of a method.@throws
or @exception
: Describes exceptions thrown by a method.@see
: Provides a reference to another method, class, or field.@deprecated
: Marks a method, field, or class as deprecated./**
* The Calculator class provides methods to perform basic arithmetic operations.
*/
public class Calculator {
/**
* Adds two integers.
* @param a the first integer
* @param b the second integer
* @return the sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
/**
* Subtracts the second integer from the first.
* @param a the first integer
* @param b the second integer
* @return the difference between a and b
*/
public int subtract(int a, int b) {
return a - b;
}
}
/**
* Returns the maximum of two integers.
*
* @param a the first integer
* @param b the second integer
* @return the maximum of a and b
*/
public int max(int a, int b) {
return (a > b) ? a : b;
}
// Increment x by 1
x = x + 1; // This is a bad comment because it restates the code