Supplier Functional Interface in Java - Quiz

Total: 5 questions

1. 

When can the Supplier interface be used?

The Supplier can be used in cases when there is no input but an output is expected.

2. 

Write an example that demonstrates how the Supplier interface returns an instance of some object.

public class Animal {
    public void move() {
        System.out.println("Move");
    }

    @Override
    public String toString() {
        return "Some Animal";
    }
}

public class TestAnimal {
    public static void main(String args[]) {
        Supplier<Animal> s = () -> new Animal();
        System.out.println(s.get());
    }
}
3. 

What is the difference between orElse and orElseGet in Optional?

orElse(value) receives an already computed value, so the expression inside the parentheses runs every time — even when the Optional is not empty. orElseGet(supplier) receives a Supplier and calls get() only for an empty Optional. When the fallback is expensive, such as a database query or object creation, orElseGet is the one you want.

Optional<User> found = repository.findById(id);

// bad: createGuest() runs every time, even when the user was found
User a = found.orElse(createGuest());

// good: createGuest() runs only for an empty Optional
User b = found.orElseGet(() -> createGuest());

// the exception object is built only when it is actually thrown
User c = found.orElseThrow(() -> new UserNotFoundException(id));
4. 

How does Supplier differ from Callable, and can get() throw a checked exception?

Their function descriptors are identical: both take nothing and return a value — () -> T. The difference is twofold. First, Callable.call() is declared as throws Exception, while Supplier.get() declares no throws clause at all, so a checked exception inside a Supplier lambda simply will not compile. Second, Callable lives in java.util.concurrent and is meant for tasks submitted to an ExecutorService, whereas Supplier from java.util.function is meant for obtaining a value lazily in ordinary code and in the Stream API.

T get();                      // Supplier, java.util.function
V call() throws Exception;    // Callable, java.util.concurrent

If a checked exception is unavoidable, there are three options: wrap it into an unchecked one such as UncheckedIOException, use Callable, or define your own functional interface with a throws clause.

5. 

Which primitive Supplier variants does java.util.function provide, and why are they needed?

Specialised suppliers of primitives exist to avoid autoboxing: a Supplier<Integer> in hot code allocates an extra object on every iteration. Each variant has its own method — not get():

IntSupplier     counter = () -> 42;              // int getAsInt()
LongSupplier    clock   = System::nanoTime;      // long getAsLong()
DoubleSupplier  random  = Math::random;          // double getAsDouble()
BooleanSupplier ready   = () -> queue.isEmpty(); // boolean getAsBoolean()

Note that there is no void version of Supplier: the interface exists precisely to produce a result. For an action with no input and no result, use Runnable with its run() method.

Page 1 of 1