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.

Answer from Dan Vinton on Stack Overflow
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);
    }
}
🌐
Baeldung
baeldung.com › home › java › core java › how to pass method as parameter in java
How to Pass Method as Parameter in Java | Baeldung
July 11, 2024 - In Java, we can pass a method as a parameter to another method using functional programming concepts, specifically using lambda expressions, method references, and functional interfaces.
Discussions

[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
methods - How to pass a function as a parameter in Java? - Stack Overflow
In Java, how can one pass a function as an argument to another function? More on stackoverflow.com
🌐 stackoverflow.com
Passing subclass as argument when superclass expected

Not only is this accepted, but also it is the correct way to do things in most Object Oriented Languages. (This is called polymorphism, which is a tenet of OOP).

Variable types should be as general as you can make them, because you might later decide to use a different subclass. If it wasn't general, you'd have to change everyplace you are using Childclass, but if it is genera (ParentClass)l you don't have to change anything.

For example if you have

public void sort(List myList)

You can pass ArrayList, LinkedList, etc. and the method would work. If you wrote that method to only accept LinkedList, then later change your mind to also include ArrayList, you'd have to change the code.

More on reddit.com
🌐 r/javahelp
14
7
September 13, 2018
Scanner as a parameter for the method?
It seems like the exercise wants you to pass in a Scanner as an argument to your inputBirthday method, rather than creating (multiple) Scanners inside the method (which you shouldn't really do). So instead, try changing your method to the following: public static void inputBirthday(Scanner input) { int day = input.nextInt(); // ... String month = input.nextLine(); // ... and so on } Be careful of the caveats of the Scanner class here. Then in your main method, create a Scanner there and pass it in: public static void main(String[] args) { Scanner scanner = new Scanner(System.in); inputBirthday(scanner); } More on reddit.com
🌐 r/javahelp
9
1
April 27, 2016
🌐
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 Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... Information can be passed to methods as a parameter.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-method-parameters
Java Method Parameters - GeeksforGeeks
July 23, 2025 - The method call has the same number of arguments and is in the same order, as the parameters. To know more, refer to the article Difference between Parameters and Arguments. ... import java.io.*; class GFG { public static void main(String[] args) { // call method pass value to the parameter // return value store in a str String str = example("GFG!"); System.out.println(str); } // para is a parameter of type String inside // method name method return String public static String example(String para) { return "Hello " + para; } }
🌐
Delft Stack
delftstack.com › home › howto › java › java pass method as parameter
How to Pass a Method as a Parameter in Java | Delft Stack
February 2, 2024 - The show method, which takes a Doable instance and a message as parameters, calls the doSomething method on the provided Doable instance (doa). The result is then printed to the console. ... This output demonstrates that the lambda expression (str) -> str + " Rohan" was successfully passed as a method to the show method, and its implementation was executed within the context of the Doable functional interface. In addition to lambda expressions, Java 8 and later versions introduce method references, providing another way to pass methods as parameters.
🌐
University of Toronto
cs.toronto.edu › ~reid › web › javaparams.html
Java Method Arguments
You can change that copy inside ... of an actual parameter. Isn't this very restrictive? Not really. In Java, we can pass a reference to an object (also called a "handle")as a parameter....
Find elsewhere
🌐
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.
🌐
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)
The Circle class has three fields: x, y, and radius. The setOrigin method has two parameters, each of which has the same name as one of the fields. Each method parameter shadows the field that shares its name. So using the simple names x or y within the body of the method refers to the parameter, not to the field.
🌐
Oracle
docs.oracle.com › javase › tutorial › reflect › member › methodparameterreflection.html
Obtaining Names of Method Parameters (The Java™ Tutorials > The Reflection API > Members)
public MethodParameterExamples$InnerClass(MethodParameterExamples) Parameter class: class MethodParameterExamples Parameter name: this$0 Modifiers: 32784 Is implicit?: true Is name present?: true Is synthetic?: false · Because the constructor of the class InnerClass is implicitly declared, its parameter is implicit as well. ... The Java compiler creates a formal parameter for the constructor of an inner class to enable the compiler to pass a reference (representing the immediately enclosing instance) from the creation expression to the member class's constructor.
🌐
Medium
dana-scheider.medium.com › parameter-passing-in-java-58858ad58a8e
Parameter Passing in Java. This is something I wrote about how… | by Dana Scheider (he/they) | Medium
March 29, 2026 - In this case, the output would ... name is now foo · To summarize, formal parameters in Java are the names that are declared as parameters at the point where a subroutine is defined....
🌐
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 - It's entirely possible that the class of which the object is an instance will have only one public method. So you might have: interface Mapper { public Object convertObject(Object a); } ... Your answer is correct up to Java 7. With Java 8 you can use lambda expressions, as u/isolatrum said. ... To my knowledge, you shouldn't act as though you will be guaranteed to get InvokeDynamic in your compile.
🌐
DEV Community
dev.to › satyam_gupta_0d1ff2152dcc › master-java-method-parameters-a-deep-dive-with-examples-best-practices-58kk
Master Java Method Parameters: A Deep Dive with Examples & Best Practices - DEV Community
October 14, 2025 - A method can have parameters but no return type (declared as void). Q3: Can I use an array instead of varargs? Yes, but varargs are more flexible. With an array, you must create and initialize the array first.
🌐
CodeGym
codegym.cc › java blog › methods in java › methods in java
Methods in Java and method parameters
So it basically pass a copy of the value of currentYear to the method and the "goToPast" only modify the copy but not currentYear itself. So to make it work, you should pass a object as the parameter of method.
Published   July 23, 2024
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:

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

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

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

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

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

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

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

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

Copynew 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:

Copypublic 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:

Copypublic int methodToPass() { 
        // do something
}

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

then call it, perhaps using an anonymous inner class:

CopydansMethod(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.

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

}
🌐
Dummies
dummies.com › article › technology › programming-web-design › java › how-to-use-methods-that-take-parameters-in-java-153263
How to Use Methods that Take Parameters in Java | dummies
July 2, 2025 - When Java passes a variable to a method via a parameter, the method itself receives a copy of the variable’s value, not the variable itself. This copy is called a pass-by-value, and it has an important consequence: If a method changes the value it receives as a parameter, that change is not reflected in the original variable that was passed to the method.
🌐
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); } }
🌐
Scientech Easy
scientecheasy.com › home › blog › how to call method with parameters in java
How to Call Method with Parameters in Java - Scientech Easy
January 15, 2026 - 3. There are two ways to call a method with parameters in Java: passing parameters of primitive data type and passing parameters of reference data type. 4. in Java, everything is passed by value whether it is reference data type or primitive ...
🌐
Kansas State University
textbooks.cs.ksu.edu › cc210 › 06-methods › 09-java › 02-parameters
Parameters :: CC 210 Textbook
June 27, 2024 - In Java, we can add parameters to a method declaration by placing them in the parentheses () at the end of the declaration. Each parameter is similar to a variable declaration, requiring both a type and an identifier.
🌐
CodingNomads
codingnomads.com › what-are-java-arguments-parameters
Method Parameters aka Arguments
While they both reside in the same spot, the word parameter generally refers to a variable that is added to the method signature, while the argument is the actual value of a specific parameter when the method is invoked.