A method declaration in Java specifies the method’s signature, including its name, return type, and parameters. It provides the compiler with information about how the method can be called but does not include the actual implementation of the method’s functionality.
public
, private
, protected
).void
, int
, String
).public int addNumbers(int a, int b);
A method definition in Java includes the method declaration and the body. The body contains the actual code that defines what the method does, including any computations, logic, and return statements.
{}
, containing the statements that define the method’s behavior.public int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
Method Declaration:
public int addNumbers(int a, int b)
int
are passed to the method.Method Body:
{
int sum = a + b;
return sum;
}
a
and b
, storing the result in the variable sum
.sum
.In Java, method declaration and definition are typically combined in a single code block within a class. Here’s a complete example with comments to illustrate both aspects:
public class Calculator {
// Method Declaration and Definition
public int addNumbers(int a, int b) {
// Method Body
int sum = a + b; // Calculate sum
return sum; // Return sum
}
// Another Method Declaration and Definition
public void printSum(int a, int b) {
int sum = addNumbers(a, b); // Call addNumbers method
System.out.println("Sum: " + sum); // Print the sum
}
// Main method to execute the program
public static void main(String[] args) {
Calculator calc = new Calculator(); // Create an instance of Calculator
calc.printSum(5, 10); // Call printSum method
}
}