What is the result of this code?
UnaryOperator<Integer> square = x -> x * x;
System.out.println(square.apply(5));
Answer: A
UnaryOperator applies the operation x * x where x = 5, resulting in 25.
Q.22Easy
Which of the following best describes a functional interface?
Answer: B
A functional interface must have exactly one abstract method, which can be implemented using lambda expressions.
Q.23Easy
What will be the output of:
Supplier<String> greeting = () -> "Hello";
System.out.println(greeting.get());
Answer: A
Supplier.get() returns the value produced by the lambda expression, which is "Hello".
Q.24Easy
Which of the following is a valid functional interface that can be used with lambda expressions?
Answer: A
A functional interface must have exactly one abstract method. This is the defining characteristic that allows it to be used with lambda expressions and method references.
Q.25Easy
Which annotation is used to mark an interface as a functional interface in Java?
Answer: B
@FunctionalInterface is the standard annotation introduced in Java 8 to explicitly mark an interface as a functional interface. It helps in compile-time checking.
Advertisement
Q.26Easy
Which of the following lambda expressions is syntactically incorrect?
Answer: C
The syntax (x, y,) is incorrect because there's a trailing comma after y. The correct syntax would be (x, y) -> x + y.
Q.27Easy
What is the purpose of a Predicate functional interface in Java?
Answer: C
Predicate<T> is a functional interface that takes a single input of type T and returns a boolean. It's commonly used for filtering operations in streams.
Q.28Easy
In a lambda expression, what does the arrow (->) operator represent?
Answer: B
The arrow (->) in lambda expressions separates the parameter list on the left from the method body on the right. It's a syntax element specific to lambda expressions.
Q.29Easy
What is the correct syntax for a lambda expression with no parameters that returns a fixed value?
Answer: B
When a lambda has no parameters, empty parentheses () are required before the arrow. Options A and D are syntactically incorrect.
Q.30Easy
Given: Function<Integer, Integer> f = x -> x * 2; Integer result = f.apply(5); What is the value of result?
Answer: B
The lambda expression x -> x * 2 multiplies the input by 2. When applied to 5, it returns 10.
Q.31Easy
Which functional interface is used to create a lambda expression that takes two integers and returns a boolean value?
Answer: A
BiPredicate<T, U> is a functional interface that takes two parameters and returns a boolean. This matches the requirement of taking two integers and returning a boolean value.
Q.32Easy
What will be the output of the following code?
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);
Answer: B
The filter operation with lambda expression (n -> n % 2 == 0) filters even numbers only. So 2 and 4 are printed, each on a new line due to println.