Java program to pass method call as arguments to another method
Here's a Java program that demonstrates how to pass a method call as an argument to another method:
public class MethodAsArgumentExample { public static void main(String[] args) { int x = 5; int y = 7; int result = calculate(x, y, MethodAsArgumentExample::sum); System.out.println("Result: " + result); } public static int sum(int a, int b) { return a + b; } public static int calculate(int a, int b, IntBinaryOperator operator) { return operator.applyAsInt(a, b); } }
Explanation:
The program defines three methods: main
, sum
, and calculate
.
The sum
method takes two integers as input and returns their sum.
The calculate
method takes two integers and an IntBinaryOperator
object as input. The IntBinaryOperator
interface defines a single method, applyAsInt
, which takes two integers as input and returns an integer. The calculate
method calls the applyAsInt
method of the IntBinaryOperator
object, passing in the two integer arguments.
The main
method declares two integer variables, x
and y
, and assigns them the values 5 and 7, respectively. It then calls the calculate
method, passing in x
, y
, and a reference to the sum
method using the MethodAsArgumentExample::sum
syntax. The calculate
method calls the applyAsInt
method of the IntBinaryOperator
object, which is the sum
method in this case, passing in the two integer arguments x
and y
. The sum
method returns the sum of the two integers, which is then returned by the calculate
method. Finally, the main
method prints the result to the console.
Note that by passing a method reference as an argument, the program is able to define the operation to be performed on the input values dynamically, without having to modify the calculate
method itself. This makes the code more flexible and reusable.