Which functional interface in Java does not return a result?

Which functional interface in Java does not return a result?

a) Supplier
b) Function
c) Consumer
d) Predicate

Answer:

c) Consumer

Explanation:

The Consumer functional interface in Java represents an operation that takes a single argument and returns no result. It is typically used for operations that consume a value but do not produce a result, such as logging, printing, or modifying objects in a collection. Here is an example:

Consumer<String> printMessage = message -> System.out.println(message); printMessage.accept("Hello, World!");  // Prints: Hello, World!

In this example, the lambda expression is assigned to a Consumer that prints a message to the console. The accept method is used to pass the argument to the lambda expression, which then performs the operation without returning any value.

The Consumer interface is a fundamental part of Java’s functional programming capabilities, enabling developers to define actions that operate on data without producing a result. This is particularly useful in scenarios where the primary goal is to perform side effects, such as updating a user interface or writing data to a log file.

Leave a Comment

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

Scroll to Top