Java Comments
Comments in Java are used to add explanations or notes to the code. Comments are ignored by the compiler and do not affect the execution of the program.
There are 3 different types of comments in Java:
- Single-line comments: These comments start with
//and are used for short explanations or notes for the java code/logic.
Example:
public class HelloWorld {
public static void main(String[] args) {
// This is a single-line comment
System.out.println("Hello, World!"); // This is also a single-line comment
}
}- Multi-line comments: These comments start with
/*and end with*/. We can keep multiple lines and are used for longer explanations or notes.
Example:
public class HelloWorld {
public static void main(String[] args) {
/* This is a multi-line comment
It can span multiple lines
and is used for longer explanations */
System.out.println("Hello, World!");
}
}- Documentation comments: These comments start with
/**and end with*/. These are used to generate documentation for the code and can include special tags like@param,@return, and@throwsto provide information about the parameters, return values, and exceptions of methods.
Example:
/**
* This class represents a simple calculator.
* which can perform addition of two numbers.
*/
public class MyCalculator {
/**
* This method adds two numbers.
*
* @param a the first number
* @param b the second number
* @return the sum of a and b
* @throws IllegalArgumentException if the input values are invalid
*/
public int add(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Numbers cannot be negative");
}
return a + b;
}
}So we can say, comments are an essential part of writing clean and maintainable code. It helps other developers (or even yourself in the future) understand the purpose and functionality of the code, making it easier to read and maintain.
See you in next page....🙂