Join our newsletter for the latest updates.
Java Program to pass methods as arguments to other methods

Java Program to pass methods as arguments to other methods

In this example, we will learn to pass methods as arguments to other methods in Java

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to pass method as a parameter to other method

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 parameter
    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 square() method. The square() method takes the method add() as its argument.

With the introduction lambda expression, now passing methods as arguments has been made easy in Java. To learn more, visit Passing Lambda Expression as method argument in Java.