Method parameters in Java allow you to pass data into a method so it can perform operations using that data. Parameters act as variables that receive values when a method is called.
A method can accept zero or more parameters. Each parameter consists of a data type and a variable name.
// Method with parameters
returnType methodName(dataType param1, dataType param2) {
// Method body uses parameters
}
// Java program demonstrating method parameters
class Calculator {
// Method that accepts two parameters
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
// Passing arguments to the method
int result = add(10, 20);
System.out.println(result);
}
}
30
The values 10 and 20 are passed as arguments to the add method. They are received by parameters a and b, then added and returned.
Enter values to simulate passing arguments to the add(int a, int b) method.