Java Lambda Expressions Interview Questions and Answers

In this article, we will discuss some important and frequently asked Java Lambda Expressions Interview Questions and Answers.
Learn Java 8 Lambda expressions with examples at Lambda Expressions guide.

1. What is a Lambda Expression?

A lambda expression is simply a function without any name. It can even be used as a parameter in a function. Lambda Expression facilitates functional programming and simplifies development a lot.

The main use of Lambda expression is to provide an implementation for functional interfaces.

Syntax of Lambda Expression 

The syntax of a lambda expression is characterized by the following three parts: 
Parameters: A lambda expression can have zero or more parameters, enclosed in parentheses. 

Arrow Token: The arrow token -> separates the parameters from the body of the lambda. 

Body: The body of the lambda contains expressions or statements describing the method's functionality.
(parameters) -> expression
Or
(parameters) -> { statements; }

Example 

Consider a simple functional interface:

@FunctionalInterface
interface MyFunction {
    int apply(int x, int y);
}
A lambda expression implementing this interface:
MyFunction add = (x, y) -> x + y;
int result = add.apply(5, 3); // result is 8
Read more in detail about lambda expressions at Java 8 Lambda Expressions

2. Why use Lambda Expression?

Lambda expressions in Java are a powerful feature that provides several key benefits:
Conciseness: Lambda expressions allow you to write instances of anonymous classes more concisely. This makes the code easier to read and maintain. 

Functional Programming: Lambda expressions enable functional programming concepts in Java. You can pass functions as method arguments, return them as values, and perform operations like mapping and filtering on collections more naturally. 

Readability: By reducing boilerplate code, lambda expressions can make the main logic of a program more apparent. The concise syntax allows for clear expression of the computation or action being performed. 

Parallel Execution Support: Lambdas work well with the Stream API, which supports parallel execution. This makes it easier to write parallel code, leveraging multicore processors without having to deal with low-level threading details. 

Less Verbose: Unlike anonymous inner classes, lambda expressions are less verbose. You don't need to name the class, declare the method, or even type the input parameters. 

Strong Typing: Lambda expressions are strongly typed. The compiler infers the types of parameters, return values, and exceptions, which can lead to more robust code. 

Scope Flexibility: Lambda expressions have access to final variables or effectively final variables from the surrounding scope, allowing more natural encapsulation of behavior. 

Interoperability: Lambdas can be used wherever functional interfaces are expected, providing great interoperability with existing code, libraries, and frameworks that use functional interfaces.

Read more in detail about lambda expressions at Java 8 Lambda Expressions.

3. Explain Lambda Expression Syntax

The syntax of a lambda expression is characterized by the following three parts: 
Parameters: A lambda expression can have zero or more parameters, enclosed in parentheses. 

Arrow Token: The arrow token -> separates the parameters from the body of the lambda. 

Body: The body of the lambda contains expressions or statements describing the method's functionality.
(parameters) -> expression
Or
(parameters) -> { statements; }
For example, Consider we have a functional interface:
interface Addable{  
    int add(int a,int b);  
} 
Let's implement the above Addable functional interface using a lambda expression:
        Addable withLambdaD = (int a,int b) -> (a+b);  
        System.out.println(withLambdaD.add(100,200)); 
Read more in detail about lambda expressions at Java 8 Lambda Expressions.

4. Which of the following are valid lambda expressions? 

A.

String a, String b -> System.out.print(a+ b);

B.

() -> return;

C.

(int i) -> i;

D.

(int i) -> i++; return i;

Answer

The correct answer is C.

Explanation 

Option C is valid. The body doesn't need to use the return keyword if it only has one statement.

5. Write a Java Lambda Expression to Create a Thread

Creating a thread using a lambda expression in Java is straightforward and concise. You can define the task you want the thread to perform as a lambda and pass it to the Thread constructor. 

Here's an example:
Runnable task = () -> {
    for (int i = 0; i < 5; i++) {
        System.out.println("Running inside the thread: " + i);
    }
};

Thread myThread = new Thread(task);
myThread.start();
Or you can simplify it further by passing the lambda expression directly to the Thread constructor:

Thread myThread = new Thread(() -> {
    for (int i = 0; i < 5; i++) {
        System.out.println("Running inside the thread: " + i);
    }
});
myThread.start();
Either way, this code creates a new thread and runs a simple loop inside it, printing a message five times. Lambda expressions make this code cleaner and more concise by removing the need to create an anonymous inner class or implement a separate class that implements Runnable.

6. How Lambda Expression and Functional Interfaces are Related?

The main use of Lambda expression is to provide an implementation for functional interfaces.

A lambda expressions provide a compact and expressive way to create instances of functional interfaces, implementing the interface's single abstract method with the body of the lambda. This relationship promotes a more functional programming style in Java, allowing for more concise and readable code.

For example, Lambda expression provides an implementation for a Printable functional interface:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
         // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}
Output :
 Print message to console....
 Print message to console....

7. Explain Various Forms of Writing Lambda Expression?

Lambda expressions in Java can be written in various forms, depending on the signature of the functional interface's abstract method they are implementing. Here are some different ways to write lambda expressions: 

No Parameters, No Return Value: 

If the abstract method takes no parameters and returns no value, the lambda expression can be written with empty parentheses and a body:
() -> System.out.println("Hello, World!");

Single Parameter, No Type Declaration: 

If the abstract method takes a single parameter, you can omit the parentheses around the parameter, and the type can be inferred:

s -> System.out.println(s);

Single Parameter, With Type Declaration: 

You can also explicitly declare the type of the parameter:

(String s) -> System.out.println(s);

Multiple Parameters: 

If the abstract method takes multiple parameters, you must include parentheses around the parameters. Types can be inferred or explicitly declared:
(a, b) -> a + b;
(int a, int b) -> a + b;

Return Statement: 

If the body of the lambda consists of a single expression that returns a value, you can write it directly:
(int a, int b) -> a + b;
If the body consists of multiple statements, you must include braces and use a return statement:
(int a, int b) -> {
    int sum = a + b;
    return sum;
};

No Parameters, Return Value: 

If the abstract method takes no parameters but returns a value, you can write it like this:
() -> 42;

Use Local Variables: 

You can also access local variables from the enclosing scope within the lambda expression:
int factor = 2;
(int a) -> a * factor;
In summary, the form of a lambda expression can vary depending on the number and types of parameters, whether you include explicit type declarations, and whether the body consists of a single expression or multiple statements. The flexibility of lambda expressions in Java allows you to write concise and expressive code that aligns with the signature of the functional interface's abstract method.

Related Java Interview Articles

Comments