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


Explain the syntax of a lambda expression


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

Explain the syntax of a lambda expression.
Answer:
The following is the syntax of a lambda expression:
(parameters)–> {lambda body}
So, a lambda expression consists of the parameters to the
expression, the lambda operator (–>) and the expression
body. A lambda expression can receive zero or more
parameters. If it does not accept any parameters, an empty
parenthesis needs to be used. If it accepts a single parameter,
the parameter need not be specified in parenthesis. If it accepts
multiple parameters, they need to be specified in parenthesis and
separated by commas. The lambda body is ordinary Java code
and can contain any number of statements. If there is a single
statement in the lambda body, the curly braces around the body
may be skipped, otherwise they need to be specified.
Give some examples of lambda expressions.
Answer:


211.
The following are some examples of lambda expressions:
Example 1– Single parameter, No return value
str–> System.out.println(str);
This lambda expression accepts one parameter and uses a
Sysout statement to print it. It does not return any value.
Example 2– Multiple parameters and a return value
(num1, num2)–> num1+num2;
This lambda expression accepts two parameters and returns the
result of adding them. The return keyword is not specified
explicitly here.
Example 3– No parameter, lambda body and return value
()–>{
//doing something here
return 0;
}
This lambda expression does not accept any parameters. It has a
body that executes some code. It returns the value 0.
Write a code sample that creates a Functional interface
and use a Lambda expression to implement it.
Answer:
A functional interface is an interface with just one abstract
method. Consider the following functional interface:
@FunctionalInterface
public interface StringConverter {


212.
public String convert(String s);
}
This code defines a functional interface called
StringConverter with a method called convert. The
convert method accepts a String value and returns a String.
A lambda expression provides an implementation for the method
in the functional interface.
So, you can then implement StringConverter interface using a
lambda expression as follows:
StringConverter converter = (str)–> str.toUpperCase();
Here, the StringConverter is implemented via a lambda
expression that converts the input String to uppercase and
returns it.

Download 1.52 Mb.

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




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