

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to pass a function as a parameter in Java
Yes. From Java 8 onwards, we can do so using method references.
Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −
Static methods
Instance methods
Constructors using new operator (TreeSet::new)
Method Reference Example
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.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.
Verify the Result
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
Output
It should produce the following output −
Mahesh Suresh Ramesh Naresh Kalpesh
- Related Questions & Answers
- How to pass an object as a parameter in JavaScript function?
- How to pass a json object as a parameter to a python function?
- How to pass a lambda expression as a method parameter in Java?
- How to pass a 2D array as a parameter in C?
- How to pass a jQuery event as a parameter in a method?
- How to pass Python function as a function argument?
- How to pass a dictionary as argument in Python function?
- How can I pass a parameter to a setTimeout() callback?
- C# Program to pass Parameter to a Thread
- How can we pass an empty string as a parameter to BIT_LENGTH() function and what would be returned by MySQL?
- Java Program to Pass ArrayList as the function argument
- How to pass arrays as function arguments in JavaScript?
- Pass long parameter to an overloaded method in Java
- How to pass entire array as an argument to a function in C language?
- Java Program to pass lambda expression as a method argument
Advertisements