Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Explain with a code sample how the same functional


Download 1.52 Mb.
Pdf ko'rish
bet80/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   76   77   78   79   80   81   82   83   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain with a code sample how the same functional
interface can be implemented differently using different
lambda expressions.
Answer:
Consider the following StringConverter functional interface:
@FunctionalInterface
public interface StringConverter {
public String convert(String s);
}
Different implementations can now be provided for the convert
methods via different lambda expressions as follows:


213.
StringConverter upperCaseconverter = str–>
str.toUpperCase();
String result = upperCaseconverter.convert(“Hello”);
Here, the StringConverter interface is implemented via a
lambda expression that converts the input String to uppercase
and returns it.
Now consider the following code:
StringConverter lowerCaseconverter = str–>
str.toLowerCase();
String result = lowerCaseconverter.convert(“Hello”);
Here, the StringConverter interface is implemented via a
lambda expression that converts the input String to lowercase
and return it.
So different lambda expressions provide different
implementations for the StringConverter interface.
Identify the error in the following lambda expression and
how it can be fixed.
(str)–> return str.toUpperCase();
Answer:
The above lambda expression uses the return keyword in the
lambda body. If the return keyword is used, the lambda body
needs to be included in curly brackets. Alternative, the return
keyword can also be removed in order to get rid of the error.
So, the above lambda expression can be fixed in either of the
following ways:


214.
215.
(str)–> {return str.toUpperCase();};
or
(str)–> str.toUpperCase();

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   76   77   78   79   80   81   82   83   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling