Question 1
The program below chains two `Consumer<String>` instances using **`andThen`**. What does it print to standard output? ```java import java.util.function.Consumer; public class Main { public static void main(String[] args) { Consumer<String> upper = s -> System.out.print(s.toUpperCase()); Consumer<String> lower = s -> System.out.print(s.toLowerCase()); Consumer<String> both = upper.andThen(lower); both.accept("Hello"); } } ```
A. HELLOhelloCorrect answer
`Consumer.andThen(after)` returns a composed consumer that performs the receiver's action first, then the `after` action on the same argument (Consumer Javadoc). `upper` runs first printing `HELLO`, then `lower` prints `hello`; both use `System.out.print`, so no newline separates them.
B. helloHELLO
Assumes the argument to `andThen` executes before the receiver — the opposite of how `andThen` works. Producing this output would require `lower.andThen(upper)` instead.
C. HELLO
Assumes `andThen` applies only the receiver and silently discards the argument consumer. The composed consumer returned by `andThen` runs both actions in order.
D. Compilation fails
`Consumer<T>` declares `andThen(Consumer<? super T> after)` as a default method and `accept(T)` as its single abstract method. The code is type-correct and compiles cleanly.
Explanation
`Consumer.andThen(after)` produces a composed `Consumer` that applies the receiver *before* `after`, both receiving the same input. Because neither lambda appends a newline (both call `System.out.print`), the two partial outputs are concatenated on a single line with the uppercase portion preceding the lowercase. Swapping which consumer is the receiver and which is the argument reverses the two halves. Treating `andThen` as though it ignores its argument would leave only the first half. `Consumer<T>` provides `andThen` as a default method, so no compilation error arises.