-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLambda-Assignment
More file actions
36 lines (27 loc) · 1.8 KB
/
Copy pathLambda-Assignment
File metadata and controls
36 lines (27 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
1. What is the lambda expression of Java 8?
Ans: As its name suggests it's an expression which allows you to write more succinct code in Java 8. For
example (a, b) -> a + b is a lambda expression (look for that arrow ->).
Which is equal to following code:
public int value(int a, int b){
return a + b;
}
It's also called an anonymous function because you are essentially writing the code you write in function but
without name.
2. Can you pass lambda expressions to a method? When?
Ans: Yes, you can pass a lambda expression to a method provided it is expecting a functional interface. For
example, if a method is accepting a Runnable, Comparable or Comparator then you can pass a lambda
expression to it because all these are functional interfaces in Java 8.
3. What is the functional interface in Java 8?
Ans: A functional interface in Java 8 is an interface with a single abstract method. For example, Comparator
which has just one abstract method called compare() or Runnable which has just one abstract method called
run(). There are many more general purpose functional interfaces introduced in JDK on java.util.function
package. They are also annotated with @FunctionalInterface but that's optional.
4. What is the benefit of lambda expressions in Java 8?
Ans: The main benefit of lambda expression in Java 8 is that now it's easier to pass a code block to a method.
Earlier, the only way to do this was wrapping the code inside an Anonymous class, which requires a lot of
boilerplate code.
5. Is it mandatory for a lambda expression to have parameters?
Ans: No, it's not mandatory for a lambda expression to have parameters, you can define a lambda expression
without parameters as shown below:
() -> System.out.println("lambdas without parameter");
You can pass this code to any method which accepts a functional interface.