What is the use of the Supplier functional interface in Java?

What is the use of the Supplier functional interface in Java?

a) To accept a single argument and return no result
b) To return a result without taking any arguments
c) To accept two arguments and return a result
d) To filter elements based on a condition

Answer:

b) To return a result without taking any arguments

Explanation:

The Supplier functional interface in Java is used to represent a function that returns a result without taking any arguments. It is often used in situations where a value needs to be generated or fetched, such as when creating new objects or providing default values. Here is an example:

Supplier<String> supplier = () -> "Hello, World!"; String message = supplier.get();  // message is "Hello, World!"

In this example, the lambda expression defines a supplier that returns the string “Hello, World!”. The get method is used to retrieve the value produced by the supplier.

The Supplier interface is a key part of Java’s functional programming capabilities, enabling developers to define operations that produce values on demand. This is particularly useful in scenarios such as lazy initialization, where a value is only generated when needed, or in dependency injection frameworks that create objects dynamically.

Leave a Comment

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

Scroll to Top