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


Is the following code valid? Explain


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

Is the following code valid? Explain.
public void generateSquareRoot(int num) {
Function squareRoot = (num)–>
Math.sqrt(num);
}
Answer:
The code above specifies a method called
generateSquareRoot. It accepts as parameter an integer
value. It then uses the in–built functional interface Function and
implements it via a lambda expression. The code is not valid and
causes a compilation error. This is because, you cannot declare a
parameter or a local variable within a lambda expression that has
the same name as a variable in the enclosing method. The
generateSquareRoot method accepts a parameter called num
and uses this same name in the lambda expression which
causes the compilation error. It can be fixed by renaming either
the method parameter or the lambda expression parameter to
something else.
Write a functional interface for which the following lambda
expression would work.
(input)–> input.toUpperCase();
Answer:


216.
The above code snippet specifies a lambda expression that
accepts a String value, converts it to uppercase and returns it.
So, it can be used to implement the following functional interface:
@FunctionalInterface
public interface Interface1 {
public String doSomething(String input);
}
This code defines a functional interface called Interface1. It
has a doSomething method that accepts as input a String and
returns a String value.
Explain how you can create a new Thread using a lambda
expression.
Answer:
The java.lang.Runnable interface is used to create a new
thread. Java 8 has designated this interface as a functional
interface and so you can implement it using a lambda expression.
The following code demonstrates this:
Runnable r = ()–> {
System.out.println(“Starting Thread..”);
//some more code
};
Thread myThread = new Thread(r);
myThread.start();
Here, the Runnable interface is implemented via a lambda
expression that has a simple Sysout statement. A new Thread
object called myThread is created with this Runnable instance.


The myThread.start() method is invoked which then spawns
a new Thread.




Download 1.52 Mb.

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




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