Given this:
class MyClass {
static class A {
public boolean property() {
return Math.random() < 0.5;
}
}
static L
One case where we can find the difference lambda expression & method reference is using as part of Supplier interface. Lets say we have below static method
public static T catchException(Supplier resolver) {
try {
T result = resolver.get();
return result ;
} catch (Exception e) {
System.out.println("Exception");
return null;
}
}
When we call the method using lambda expression as below, code work fine since the lambda expression passed as part of Supplier & executed only when get() method is called where the exception is caught.
List underlyers=null;
System.out.println(catchException(()->underlyers.size()));
When we call the method using method reference as below, we get NullPointerExecption before calling the method since the reference is executed before passing in to the supplier. The control does not reach get() method in this case.
List underlyers=null;
System.out.println(catchException(underlyers::size));