π§ What is a Method Reference?
AΒ Method Reference is a shorthand syntax for calling a method via a lambda expression, using the :: operator.
β It helps make your code more concise and readable when the lambda simply calls a method.
π§ General Syntax
π§© Types of Method References
| Type | Syntax Example | Use Case Example |
|---|---|---|
| 1οΈβ£ Static Method | ClassName::staticMethod |
Integer::parseInt |
| 2οΈβ£ Instance Method (of a specific object) | obj::instanceMethod |
System.out::println |
| 3οΈβ£ Instance Method (of arbitrary object of a class) | ClassName::instanceMethod |
String::toLowerCase |
| 4οΈβ£ Constructor Reference | ClassName::new |
ArrayList::new |
β Examples
1. Static Method Reference
2. Instance Method of a Particular Object
3. Instance Method of Arbitrary Object
4. Constructor Reference
π― When to Use
Use :: only when the lambda expression:
- Only calls a method
- Doesnβt need to modify arguments
- Keeps code clean and expressive
π Summary
| Feature | Value |
|---|---|
| Symbol |
:: (double colon) |
| Purpose | Shortens lambda expressions |
| Introduced In | Java 8 |
| Works With | Lambdas, Streams, Functional Interfaces |
| Readability | β Improves |