We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method.
// pass method2 as argument to method1
public void method1(method2());
Here, the returned value from method2() is assigned as an argument to method1().
If we need to pass the actual method as an argument, we use the lambda expression. To learn more, visit Passing Lambda Expression as method argument in Java.
Example: Java Program to Pass Method as Argument
class Main {
// calculate the sum
public int add(int a, int b) {
// calculate sum
int sum = a + b;
return sum;
}
// calculate the square
public void square(int num) {
int result = num * num;
System.out.println(result); // prints 576
}
public static void main(String[] args) {
Main obj = new Main();
// call the square() method
// passing add() as an argument
obj.square(obj.add(15, 9));
}
}
In the above example, we have created two methods named square()
and add()
. Notice the line,
obj.square(obj.add(15, 9));
Here, we are calling the add()
method as the argument of the square()
method. Hence, the returned value from add()
is passed as argument to square()
.