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);
    }

}
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
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....
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);
    }
}
🌐
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 ...
🌐
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.
🌐
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.
🌐
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.
🌐
Techndeck
techndeck.com › how-to-pass-function-as-a-parameter-in-a-method-in-java-8
Pass Function as a Parameter in a Method in Java 8 - Techndeck
April 20, 2022 - Simplest example of Higher Order Function (passing one function to another as an parameter or argument) in Java 8...!!!
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › How-to-pass-a-function-as-a-parameter-in-Java
How to pass a function as a parameter in Java
June 17, 2020 - 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.
🌐
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; } }
🌐
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.
🌐
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......
🌐
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
🌐
Blogger
self-learning-java-tutorial.blogspot.com › 2020 › 01 › how-to-pass-method-as-parameter-in-java.html
Programming for beginners: How to pass method as a parameter in Java?
The only condition is that the methods should be assignable to any Functional Interface. ... Above statement refer println method. ... package com.sample.app; import java.util.Arrays; import java.util.List; public class App { public static void main(String args[]) { List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11); primes.stream().forEach(System.out::println); } }
🌐
Baeldung
baeldung.com › home › java › lambda expressions and functional interfaces: tips and best practices
Lambda Expressions and Functional Interfaces: Tips and Best Practices | Baeldung
December 16, 2023 - Functional interfaces, which are gathered in the java.util.function package, satisfy most developers’ needs in providing target types for lambda expressions and method references. Each of these interfaces is general and abstract, making them easy to adapt to almost any lambda expression. Developers should explore this package before creating new functional interfaces. ... In addition, we have a method add() in some class UseFoo, which takes this interface as a parameter:
🌐
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.
🌐
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
It allows you to: Write reusable, flexible code (e.g., a single method that can perform different operations based on the passed function). Simplify callback logic (e.g., event handlers, async operations).
🌐
Randecook
randecook.ca › post › java-pass-function-as-parameter
Randecook
October 19, 2024 - This method represents the function you want to pass. ... This MyFunction interface defines a single method apply(), which takes an integer as input and returns an integer. Now, let's create a method that accepts a MyFunction as a parameter: public class FunctionExample { public static int operate(int x, MyFunction function) { return function.apply(x); } public static void main(String[] args) { // Example usage MyFunction square = x -> x * x; MyFunction cube = x -> x * x * x; System.out.println(operate(5, square)); // Output: 25 System.out.println(operate(5, cube)); // Output: 125 } }
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › arguments.html
Passing Information to a Method or a Constructor (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
So using the simple names x or y within the body of the method refers to the parameter, not to the field. To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled "Using the this Keyword." Primitive arguments, such as an int or a double, are passed into methods by value.