Explain method references

Method references are a shorthand notation of a lambda expression to call a method. They help to write more readable and concise code in Java. A method reference can be used where a functional interface is expected. The syntax consists of the class name or the object followed by the double colon (::) operator, and then the method name. There are four types of method references:

  • Static Method Reference
  • Instance Method Reference of a Particular Object
  • Instance Method Reference of an Arbitrary Object of a Particular Type
  • Constructor Reference

Here's an example of how to use method references in Java:

// Static method reference class StringUtils { public static String toUpperCase(String str) { return str.toUpperCase(); } } // Main class public class Example { public static void main(String[] args) { List names = Arrays.asList("Alice", "Bob", "Charlie"); // Using method reference names.forEach(name -> System.out.println(StringUtils.toUpperCase(name))); } }

method references Java lambda expressions functional interface static method reference example