DEV Community

Cover image for Confusion Around Method Referencing
Saami abbas Khan
Saami abbas Khan

Posted on

2

Confusion Around Method Referencing

Method references in Java provide a way to refer to methodsor constructorswithout invoking them explicitly. They can be thought of as a shorthand for writing simple lambda expressions.

Majorly method referencing can either be static or related to an instance:

Integer::sum;
System.out::println;
Enter fullscreen mode Exit fullscreen mode

These are examples of static method references (also known as bound referencing).

However, consider this:

String::concat
Enter fullscreen mode Exit fullscreen mode

Here, concatis not a static method, so how is this working? This is an example of unbound referencing. The compiler understands that this is an instance method reference based on how our code is written. This makes it possible to simplify method calls like this.

The way we write our code determines these types of references (especially unbound ones). Taking concatas an example:

((a, b) -> a + b, "Hello", "World");
// ----------------Is same as -------------
((a, b) -> a.concat(b), "Hello", "World"); // This one could be replaced by mehod referencing

// ----------------Alternative-------------

(String::concat, "Hello", "World");

/* The use of 'a' as the first parameter and calling `concat `of 'a' itself 
gives the compiler an idea of how it should decode `String::concat`*/
Enter fullscreen mode Exit fullscreen mode

So, instead of writing out a full lambda, we can simplify with a method reference.

Keep Learning 🚀

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay