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
πΉ 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);
π 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);
β 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;
πΉ 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)