Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing non final objects to method references [duplicate]

What is the explanation that s.get() returns "ONE" the second time as well?

String x = "one";
Supplier<String> s = x::toUpperCase;
System.out.println("s.get() = " + s.get());
x = "two";
System.out.println("s.get() = " + s.get());

Update:

Compare it to:

String x = "one";
Supplier<String> s = () -> x.toUpperCase();
System.out.println("s.get() = " + s.get());
x = "two";
System.out.println("s.get() = " + s.get());

It will throw a compilation error.

like image 945
Stephen L. Avatar asked Feb 08 '17 12:02

Stephen L.


1 Answers

In java variables referring an objects are usually called as references. In the above code you have two references , x and s.

Strings are immutable and any change done, represents another Object. Once created you can not modify any state of the String object.

In the code both x and s are initilized to refer 2 objects and then x is made to refer another object, but s still refers to same object. note that :: is evaluated immediately and resulting object is assiged. x can change its reference to another object independent of y

Using x = "two" only makes x to refer to a different object.

like image 94
nits.kk Avatar answered Nov 15 '22 13:11

nits.kk