English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Java programs pass methods as parameters to other methods

    Java Examples Comprehensive

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:

Example1:The Java program passes methods as parameters to other methods

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.

Java Examples Comprehensive