DEV Community

Gowtham Kalyan
Gowtham Kalyan

Posted on

What is Method Reference (::) in Java 8? A Complete Guide

Java 8 introduced several powerful features to make code more concise and functional. One of the most useful among them is the Method Reference (::).

If you’re working with Lambda Expressions, understanding method references will take your code to the next level.


πŸ”Ή What is Method Reference?

A Method Reference is a shorthand syntax used to refer to a method without executing it.

πŸ‘‰ It is represented using the :: operator.

Instead of writing a lambda expression, you can directly reference an existing method.


πŸ”Ή Basic Syntax

ClassName::methodName
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Why Use Method Reference?

  • βœ… Reduces code length
  • βœ… Improves readability
  • βœ… Reuses existing methods
  • βœ… Works seamlessly with functional interfaces

πŸ”Ή Example: Lambda vs Method Reference

Using Lambda:

```java id="h5t1hp"
list.forEach(x -> System.out.println(x));




### Using Method Reference:



```java id="5h0l1c"
list.forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Cleaner and more readable!


πŸ”Ή Types of Method References

βœ… 1. Static Method Reference

```java id="9o0bzz"
class Demo {
static void display(String msg) {
System.out.println(msg);
}
}

list.forEach(Demo::display);




---

### βœ… 2. Instance Method Reference (of a Particular Object)



```java id="h2p5fw"
class Demo {
    void show(String msg) {
        System.out.println(msg);
    }
}

Demo d = new Demo();
list.forEach(d::show);
Enter fullscreen mode Exit fullscreen mode

βœ… 3. Instance Method Reference (of Arbitrary Object)

```java id="9re4hj"
list.sort(String::compareToIgnoreCase);




---

### βœ… 4. Constructor Reference



```java id="u6k0g6"
Supplier<List<String>> supplier = ArrayList::new;
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή When to Use Method Reference?

πŸ‘‰ Use method references when:

  • You already have a method that matches a functional interface
  • You want cleaner and shorter code
  • You are working with Streams API

πŸ”Ή Real-Time Use Cases

  • Iterating collections (forEach)
  • Sorting data (Comparator)
  • Stream operations (map, filter)
  • Object creation using constructors

πŸ”₯ Key Difference: Lambda vs Method Reference

Feature Lambda Expression Method Reference
Syntax Verbose Short & Clean
Reusability Limited High
Readability Medium High

πŸš€ Final Thoughts

Method references are a powerful feature in Java 8 that help you write clean, readable, and efficient code. Once you start using them with Streams and functional interfaces, your coding style becomes more modern and professional.


🎯 Learn More – Upgrade Your Java Skills

Join the Best Core JAVA Online Training in Hyderabad and gain hands-on experience with real-time projects, expert guidance, and interview preparation.

Top comments (0)