What does the Local-Variable Syntax for Lambda Parameters in Java 11 allow you to do?

Java MCQ: What does the Local-Variable Syntax for Lambda Parameters in Java 11 allow you to do?

a) Define local variables in lambda expressions
b) Use the var keyword to declare the types of lambda parameters
c) Use instance variables inside lambda expressions
d) Automatically infer the types of lambda parameters

Answer:

b) Use the var keyword to declare the types of lambda parameters

Explanation:

The Local-Variable Syntax for Lambda Parameters, introduced in Java 11, allows you to use the var keyword to declare the types of lambda parameters. This feature provides consistency with local variable declarations, where var can be used to infer the type. However, all lambda parameters must be either explicitly typed with var or all must be untyped; a mix of typed and untyped parameters is not allowed.

Here’s an example of using var in a lambda expression:

import java.util.List;
import java.util.stream.Collectors;

public class VarInLambdaExample {
    public static void main(String[] args) {
        List<String> names = List.of("John", "Jane", "Jack");
        List<String> uppercasedNames = names.stream()
                                                .map((var name) -> name.toUpperCase())
                                                .collect(Collectors.toList());

        System.out.println(uppercasedNames);
    }
}

In this example, var is used to declare the type of the lambda parameter name. The compiler infers that name is a String based on the context.

The Local-Variable Syntax for Lambda Parameters enhances code readability and consistency when using var across different parts of a Java program.

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