English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to pass methods as parameters to other methods in Java
To understand this example, you should know the followingJava ProgrammingTopic:
class Main { //Calculate the total sum public int add(int a, int b) { //Calculate the total sum int sum = a + b; return sum; } //Calculate 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(); // Calling the square() method // Passing add() as a parameter obj.square(obj.add(15, 9)); } }
In the above example, we created two methods named square() and add(). Note this line,
obj.square(obj.add(15, 9));
Here, we are calling the square() method. The square() method takes the add() method as its parameter.
With the introduction of lambda expressions, it has become easier to pass methods as parameters in Java. For more information, please visitJava Lambda Expressions as Method Parameters.