Method References Java Flashcards

(8 cards)

1
Q

What is a method reference

A

It is basically a pointer to a function
class Counter {
private int count = 0;

public void increment() {
    count++;
}

public int getCount() {
    return count;
} } Counter counter = new Counter(); Runnable action = counter::increment; action.run(); action.run(); System.out.println(counter.getCount()); // 2  Here counter::increment is a pointer to the function When action.run() is called - increment() is called on the specific counter object. It doesn’t copy the object — it calls the real method and mutates that same instance.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Type 1 : Static Method

A

ClassName::staticMethod

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Type 2: Instance method of a particular object

A

Instance method of a particular object
instance::methodName
Calls a method on a specific object - That means if I use this in a stream operation method belonging to SAME object will be called again and again

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Instance method of an arbitrary object of a type
A

ClassName::instanceMethod
Calls a method on each element. That means if I use this in a stream operation method belonging to DIFFERENT object from the stream will be called. So you stream should be of type ClassName so that you are calling the methods on a unique object each time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. Constructor reference
A

ClassName::new
Creates a new object
Equivalent to () -> new ClassName()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

State Mutation

A

Since the method reference has access to private variables of the Object, you can technically modify the value of the variables, but this is not recommended, unless you have a strong reason for doing so

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Lambda

A

Easier to think of it as a pointer to a function
(x, y) -> x + y
(parameters) -> { statements }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can i refer a variable from outside the lambda’s scope in the lambda

A

Only if they are Final or effectively final local variables
int base = 10;
Function<Integer, Integer> adder = x -> x + base;
System.out.println(adder.apply(5));
“Effectively Final” - You can use an outside variable inside a lambda only if it is not modified after it’s defined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly