interface HelloWorld {
String hello(String s);
}
public static void main(String[] args) {
HelloWorld h = String::new;
System.out.println(h.hello("dasdasdadasd"));
}
When I execute the above method,it returns the value which I am passing in the arguments dasdasdadasd Which method of string class is executed or is there any default implementation which java provides at runtime or by default it calls supplier.get() method?
h was assigned a method reference to the public String(String original) constructor of the String class. That's the only constructor that matches the signature of the String hello(String s) method of your HelloWorld interface.
Therefore h.hello("dasdasdadasd") creates a new String instance whose value is equal to "dasdasdadasd" and returns that instance.
HelloWorld h = String::new;
is equivalent to:
HelloWorld h = s -> new String(s);
Your code can be rewritten as:
hw returns a string created from what it receives:
//Returns a string based on the input
HelloWorld hw = (s) -> {
return new String(s);
};
Invoking hello() on that object returns "basically" the input:
//The value assigned to print is "dasdasdadasd", as returned by hw
String print = hw.hello("dasdasdadasd");
println Is receiving dasdasdadasd:
System.out.println(print); //"dasdasdadasd" is passed to println
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