Java 8 and above

Using Java 8+ lambda expressions, if you have a class or interface with only a single abstract method (sometimes called a SAM type), for example:

public interface MyInterface {
    String doSomething(int param1, String param2);
}

then anywhere where MyInterface is used, you can substitute a lambda expression:

class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}

For example, you can create a new thread very quickly:

new Thread(() -> someMethod()).start();

And use the method reference syntax to make it even cleaner:

new Thread(this::someMethod).start();

Without lambda expressions, these last two examples would look like:

new Thread(new Runnable() { someMethod(); }).start();

Before Java 8

A common pattern would be to 'wrap' it within an interface, like Callable, for example, then you pass in a Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}

This pattern is known as the Command Pattern.

Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.

In response to your comment below you could say:

public int methodToPass() { 
        // do something
}

public void dansMethod(int i, Callable<Integer> myFunc) {
       // do something
}

then call it, perhaps using an anonymous inner class:

dansMethod(100, new Callable<Integer>() {
   public Integer call() {
        return methodToPass();
   }
});

Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.

Answer from jk. on Stack Overflow
Top answer
1 of 8
594

Java 8 and above

Using Java 8+ lambda expressions, if you have a class or interface with only a single abstract method (sometimes called a SAM type), for example:

public interface MyInterface {
    String doSomething(int param1, String param2);
}

then anywhere where MyInterface is used, you can substitute a lambda expression:

class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}

For example, you can create a new thread very quickly:

new Thread(() -> someMethod()).start();

And use the method reference syntax to make it even cleaner:

new Thread(this::someMethod).start();

Without lambda expressions, these last two examples would look like:

new Thread(new Runnable() { someMethod(); }).start();

Before Java 8

A common pattern would be to 'wrap' it within an interface, like Callable, for example, then you pass in a Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}

This pattern is known as the Command Pattern.

Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.

In response to your comment below you could say:

public int methodToPass() { 
        // do something
}

public void dansMethod(int i, Callable<Integer> myFunc) {
       // do something
}

then call it, perhaps using an anonymous inner class:

dansMethod(100, new Callable<Integer>() {
   public Integer call() {
        return methodToPass();
   }
});

Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.

2 of 8
133

You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.

import java.lang.reflect.Method;

public class Demo {

    public static void main(String[] args) throws Exception{
        Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        Method method1 = Demo.class.getMethod("method1", parameterTypes);

        Demo demo = new Demo();
        demo.method2(demo, method1, "Hello World");
    }

    public void method1(String message) {
        System.out.println(message);
    }

    public void method2(Object object, Method method, String message) throws Exception {
        Object[] parameters = new Object[1];
        parameters[0] = message;
        method.invoke(object, parameters);
    }

}
🌐
W3Docs
w3docs.com › java
How to pass a function as a parameter in Java?
Function sayHello = () -> ... single abstract method called apply(). The runFunction() method takes a Function as a parameter and calls the apply() method on it when it is called....
Discussions

interface - Java Pass Method as Parameter - Stack Overflow
I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative. I've been told interfaces are the More on stackoverflow.com
🌐 stackoverflow.com
How to use a function as a parameter? - Processing Forum
Yes, in Java, you cannot pass a function or a reference to a function. Usually, you make a class (or an interface) to wrap the function. That's the case of the Comparator interface, to name only one commonly used here. A bit verbose / heavy, but it works. ... There's no way of passing functions as parameters... More on forum.processing.org
🌐 forum.processing.org
October 20, 2012
[Java] How do I pass a method as a parameter to another method?
you use a lambda, aka an anonymous function: https://stackoverflow.com/questions/2755445/how-can-i-write-an-anonymous-function-in-java More on reddit.com
🌐 r/learnprogramming
5
1
September 15, 2017
java - Pass function as value for another function - Stack Overflow
I've been trying to find out how to do this, but can't seem to find a good result. What I'm trying to do is pass a function in another function, and then get the result (in the actual code it would... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
14

Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda

For starters, your test function is wrong in multiple places:

boolean test(function someSortFunction){//This is not how you pass functions
    int n; //this has to be initialized
    for (int i=0; i<=n ; i++) {//Depending on how n is used, you may have to use < instead of <=
        int[] A = generateArray()//Missing semi-colon
        if (isSorted(someSortFunction(A)) = false) {//Comparing is done with ==, not =
            return false;
        }
    }
    return true;
}

In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)

Supplier defines return type, Consumer defines input type, and function both. Meaning:

  • Use Predicate when you have a boolean return type with arguments
  • Use Supplier when you have a return type
  • Use Consumer when you have an argument
  • Use Function when you have both an argument and a return value

Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:

boolean test(Function<int[], int[]> someFunction) 

Using Function requires calling apply to execute the method:

int[] res = someFunction.apply(input);

Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:

public class ManyFunctions {...}
public class MainClass {...}

Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:

ManyFunctions functions = new ManyFunctions();

now, you pass the functions:

test(functions::mergeSort);

if you make the methods static, you can just skip the instance and use the class name directly:

test(ManyFunctions::mergeSort);

So your class would be:

class MainClass{
    public static void main(String[] args){
        ManyFunctions manyFunctions = new ManyFunctions();
        test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
        test(manyFunctions::otherSort);

    }

    boolean test(Function<int[], int[]> someSortFunction){
        int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
        for (int i=0; i<=n ; i++) {
            int[] A = generateArray();
            if (isSorted(someSortFunction.apply(A)) == false) {//comparing is done with ==
                return false;
            }
         }
         return true;
    }
}//Don't know if it was a copy-paste problem or not, but you had a missing bracket
🌐
W3Docs
w3docs.com › java
Java Pass Method as Parameter
For example: @FunctionalInterface public interface MyFunction { void apply(); } ... To pass a method as a parameter, you can create a lambda expression that implements the abstract method of the functional interface.
🌐
Delft Stack
delftstack.com › home › howto › java › how to pass a function as a parameter in java
How to Pass a Function as a Parameter in Java | Delft Stack
February 2, 2024 - There is no difference in how we define functionToPass; however, we need to follow a specific syntax to define the outerFunction: outerFunction(Object object, Method method, param1, param2, ...). ... import java.lang.reflect.Method; public class ...
🌐
Medium
medium.com › @mibatman01 › pass-function-as-a-parameter-without-using-lambdas-in-java-5e002bbc3516
Pass “function” as a parameter without using “Lambdas” in JAVA | by shivam vishwakarma | Medium
August 3, 2023 - We can do the same without “Anonymous” function, all we need to explicitly create the class and implement the interface. public class Num { List<Integer>nums=new ArrayList<>(); Num() { //Adding integer into the list nums.add(1); nums.add(2); nums.add(3); nums.add(4); nums.add(5); nums.add(6); } //Passed the object of the Interface implementation //which contains the method test() public List<Integer>evenNum(CheckNum checkNum) { List<Integer>evenNumsList=new ArrayList<>(); for(var num:nums) if(checkNum.test(num)) evenNumsList.add(num); return evenNumsList; } }
Top answer
1 of 16
291

As of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier...


Take a look at the command pattern.

// NOTE: code not tested, but I believe this is valid java...
public class CommandExample 
{
    public interface Command 
    {
        public void execute(Object data);
    }

    public class PrintCommand implements Command 
    {
        public void execute(Object data) 
        {
            System.out.println(data.toString());
        }    
    }

    public static void callCommand(Command command, Object data) 
    {
        command.execute(data);
    }

    public static void main(String... args) 
    {
        callCommand(new PrintCommand(), "hello world");
    }
}

As Pete Kirkham points out, there's another way of doing this using a Visitor. The visitor approach is a little more involved - your nodes all need to be visitor-aware with an acceptVisitor() method - but if you need to traverse a more complex object graph, then it's worth examining.

2 of 16
117

In Java 8, you can now pass a method more easily using Lambda Expressions and Method References. First, some background: a functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

Without lambda expressions:

obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});

With lambda expressions:

obj.aMethod(i -> i == 982);

Here is an excerpt from the Java tutorial on Lambda Expressions:

Syntax of Lambda Expressions

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.

    Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

    p -> p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    
  • The arrow token, ->

  • A body, which consists of a single expression or a statement block. This example uses the following expression:

    p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

    p -> {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }
    

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)
    

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.


Here is how you can "pass a method" using a lambda expression:

interface I {
    public void myMethod(Component component);
}

class A {
    public void changeColor(Component component) {
        // code here
    }

    public void changeSize(Component component) {
        // code here
    }
}
class B {
    public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
        for(Component leaf : myComponentArray) {
            if(leaf instanceof Container) { // recursive call if Container
                Container node = (Container)leaf;
                setAllComponents(node.getComponents(), myMethodInterface);
            } // end if node
            myMethodsInterface.myMethod(leaf);
        } // end looping through components
    }
}
class C {
    A a = new A();
    B b = new B();

    public C() {
        b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
        b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
    }
}

Class C can be shortened even a bit further by the use of method references like so:

class C {
    A a = new A();
    B b = new B();

    public C() {
        b.setAllComponents(this.getComponents(), a::changeColor);
        b.setAllComponents(this.getComponents(), a::changeSize);
    }
}
Find elsewhere
🌐
Quora
quora.com › In-Java-can-you-pass-a-function-as-an-argument-to-another-function-excluding-lambdas
In Java, can you pass a function as an argument to another function, excluding lambdas? - Quora
Answer (1 of 3): Yes we can pass function as an argument using functional Interface For creating a reference to a lambda we use a functional interface where the functional method has the same signature as the lambda expression.
🌐
TutorialsPoint
tutorialspoint.com › how-to-pass-a-function-as-a-parameter-in-java
How to pass a function as a parameter in Java
import java.util.List; import java.util.ArrayList; public class Java8Tester { public static void main(String args[]) { List names = new ArrayList(); names.add("Mahesh"); names.add("Suresh"); names.add("Ramesh"); names.add("Naresh"); names.add("Kalpesh"); names.forEach(System.out::println); } } Here we have passed System.out::println method as a static method reference.
🌐
Processing Forum
forum.processing.org › one › topic › how-to-use-a-function-as-a-parameter.html
How to use a function as a parameter? - Processing Forum
October 20, 2012 - Yes, in Java, you cannot pass a ... interface, to name only one commonly used here. A bit verbose / heavy, but it works. ... There's no way of passing functions as parameters......
🌐
javathinking
javathinking.com › blog › how-to-pass-a-function-as-a-parameter-in-java
How to Pass a Function as a Parameter in Java: Step-by-Step Guide with Examples — javathinking.com
This technique promotes code reusability, flexibility, and readability, especially when combined with the Streams API and modern Java features. By following the steps outlined in this guide—defining a functional interface, creating a method that accepts it, implementing it with a lambda, and passing it to the method—you can leverage the power of behavior parameterization in your Java applications.
🌐
Programiz
programiz.com › java-programming › examples › passing-method-as-argument
Java Program to Pass the Result of One Method Call to Another 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 an argument obj.square(obj.add(15, 9)); } } In the above example, we have created two methods named square() and add(). Notice the line, ... Here, we are calling the add() method as the argument of the square() method.
🌐
javaspring
javaspring.net › blog › java-passing-function-as-parameter
Java: Passing Functions as Parameters — javaspring.net
This blog post will explore the fundamental concepts, usage methods, common practices, and best practices of passing functions as parameters in Java.
🌐
Baeldung
baeldung.com › home › java › how to pass method as parameter in java
How to Pass Method as Parameter in Java | Baeldung
July 11, 2024 - This lambda expression (a, b) -> a + b represents a function that sums its two inputs. The integers 5 and 3 are passed as the second and third arguments respectively. Finally, we use an assertion to verify that our implementation works as expected: ... We can also use Callable to pass methods as parameters. The Callable interface is part of the java.util.concurrent package and represents a task that returns a result and may throw an exception.
🌐
W3Schools
w3schools.com › java › java_methods_param.asp
Java Method Parameters
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... Information can be passed to methods as a parameter.
🌐
Reddit
reddit.com › r/learnprogramming › [java] how do i pass a method as a parameter to another method?
[Java] How do I pass a method as a parameter to another method? : r/learnprogramming
September 15, 2017 - I'd check out this stack overflow answer on passing functions as parameters. ... You can't pass methods in Java (edit: Not true in Java 8, which has lambdas). You have to pass an object.
🌐
GeeksforGeeks
geeksforgeeks.org › java › parameter-passing-techniques-in-java-with-examples
Parameter Passing Techniques in Java with Examples - GeeksforGeeks
July 11, 2025 - 2. Call by reference(aliasing): Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space. ... // Java program to illustrate // Call by Reference // Callee class CallByReference { int a, b; // Function to assign the value // to the class variables CallByReference(int x, int y) { a = x; b
🌐
Codemia
codemia.io › knowledge-hub › path › how_to_pass_a_function_as_a_parameter_in_java
How to pass a function as a parameter in Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Quora
quora.com › In-Java-can-a-method-accept-another-method-as-a-parameter
In Java, can a method accept another method as a parameter? - Quora
Define or use a standard functional interface from java.util.function (Supplier, Consumer, Function, Predicate, BiFunction, Runnable, etc.). ... Short answer: Yes — indirectly. Java cannot pass raw method pointers like C function pointers, ...