Page 1 of 1

About Question enthuware.ocpjp.v8.2.1900 :

Posted: Fri Feb 09, 2018 9:12 pm
by jorgeruiz
The first option is in fact a wrong answer. And it performs as in the explanation.

However,
Why the lambda in the first call to forEach() is not treated as a Function/UnuaryOperator instead of a Consumer since the String.toUpperCase() returns a String?

Code: Select all

letters.forEach(letter->letter.toUpperCase());

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Fri Feb 09, 2018 11:15 pm
by admin
Because the forEach method is defined to expect a Consumer as an argument and not a Function.

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Sun Feb 11, 2018 11:28 pm
by jorgeruiz
Yes, but that should not cause the code to not compile since the lambda is returning a value meanwhile the return type of Consumer is void?

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Mon Feb 12, 2018 12:54 am
by admin
Sorry, not sure what you mean. What should not cause what to not compile? A method that returns void can call a method that returns anything within its body -
void m(){
methodThatReturnsSomething(); //no problem here. return value is ignored
}

But if a method expects a Consumer as argument, you can't pass it a Function (and vice versa).
So I am not sure what is the confusion.

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Mon Feb 12, 2018 5:02 pm
by jorgeruiz
Ok. I got you.
Since forEach expects a Consumer. What is happening here is:

Code: Select all

(String s) -> { "somestring".toUpperCase(); }
What I was thinking is, if the toUpperCase() method returns a value, then the lambda should be treated as a Function:

Code: Select all

 (String s) -> { RETURN "somestring".toUpperCase(); }
I'm sorry my question got confused.
Thanks.

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Sun Nov 25, 2018 10:21 am
by gfinesch
The first statement does convert each element to upper case. However, the new upper case value does not get back in the the list. It is lost. Therefore, the second statement still prints the lower case value.
Does the upper case value get lost because of String's immutability, right?

In fact, were it be like

Code: Select all

 List<StringBuilder> letters = Arrays.asList(new StringBuilder ("j"), new StringBuilder("a"), new StringBuilder("v"),new StringBuilder("a")); 
 letters.forEach(letter->letter.append("BYE")); 
letters.forEach(System.out::print);
The output would have been

Code: Select all

jBYEaBYEvBYEaBYE
Thanks!

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Sun Nov 25, 2018 10:37 am
by admin
That's right. But you should try it out :)

Re: About Question enthuware.ocpjp.v8.2.1900 :

Posted: Sun Dec 02, 2018 8:56 am
by gfinesch
Thank you. Yes, I tied it out. I just wanted to be 100% sure why it works that way.