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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With