In Java, a method is a block of code that performs a specific task. Methods help in code reusability, modular programming, and better readability. A method must be declared before it can be called.
A method declaration consists of:
// General syntax of a method declaration in Java
accessModifier returnType methodName(parameters) {
// method body
}
// Example demonstrating method declaration and calling
class Calculator {
// Method declaration
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
// Method calling
int result = add(10, 20);
System.out.println(result);
}
}
30
The add() method receives two integers, adds them, and returns the result. The returned value is stored in the variable result and printed.
Enter values below to simulate calling the add() method dynamically.