Which of the following is a valid example of a lambda expression in Java?

Java MCQ: Which of the following is a valid example of a lambda expression in Java?

a) int add(int a, int b)
b) (a, b) -> a + b
c) a + b => int
d) lambda(int a, int b) { return a + b; }

Answer:

b) (a, b) -> a + b

Explanation:

The syntax (a, b) -> a + b is a valid example of a lambda expression in Java. This expression represents a function that takes two parameters (a and b) and returns their sum. The arrow -> separates the parameters from the expression body.

Lambdas in Java have the following general syntax:

(parameters) -> expression

or

(parameters) -> { statements }

For example:

(int x, int y) -> x + y

This expression represents a function that adds two integers.

Lambdas are used extensively with functional interfaces, which are interfaces with a single abstract method, such as Runnable, Comparator, or custom interfaces. They provide a concise way to define the behavior in a functional programming style.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top