0
0
JavaConceptBeginner · 3 min read

What is Method Reference in Java: Simple Explanation and Example

In Java, a method reference is a shorthand syntax to call a method directly by referring to it with ::. It makes code simpler and more readable by replacing lambda expressions that just call a method.
⚙️

How It Works

Think of a method reference as a shortcut to calling a method without writing the full lambda expression. Instead of writing a small function that calls another method, you just point to that method directly using ::. This is like giving someone a direct phone number instead of explaining how to reach a person step-by-step.

For example, if you want to print each item in a list, instead of writing a lambda like item -> System.out.println(item), you can use a method reference System.out::println. Java figures out the right way to call the method based on the context.

This makes your code cleaner and easier to read, especially when you are passing simple method calls as arguments to other methods.

💻

Example

This example shows how to use a method reference to print each name in a list instead of using a lambda expression.

java
import java.util.List;

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie");

        // Using lambda expression
        names.forEach(name -> System.out.println(name));

        // Using method reference
        names.forEach(System.out::println);
    }
}
Output
Alice Bob Charlie Alice Bob Charlie
🎯

When to Use

Use method references when you want to pass a method as an argument and the method already exists with the right signature. It helps simplify code by removing unnecessary lambda expressions.

Common real-world uses include:

  • Printing or logging items in a collection.
  • Sorting or comparing objects using existing methods.
  • Transforming data by calling existing static or instance methods.

They are especially useful in functional programming styles with streams and collections.

Key Points

  • Method references use the :: operator to refer to methods.
  • They replace simple lambda expressions that just call a method.
  • There are four types: static method references, instance method references of a particular object, instance method references of an arbitrary object of a type, and constructor references.
  • They improve code readability and conciseness.

Key Takeaways

Method references simplify code by directly referring to existing methods using ::.
They replace simple lambda expressions that only call a method.
Use method references to make code cleaner when passing methods as arguments.
There are different types of method references for static, instance, and constructor methods.
They are commonly used with collections and streams for readable functional-style code.