Question 7
Back to Exercise
What is the output of the following Java program?
import java.util.function.Supplier;
public class Main {
static String expensive(String tag) { System.out.print("[computing " + tag + "] "); return tag.toUpperCase(); }
static String orDefault(String value, Supplier<String> fallback) { return value != null ? value : fallback.get(); }
public static void main(String[] args) {
String a = orDefault("given", () -> expensive("a"));
String b = orDefault(null, () -> expensive("b"));
System.out.println(a + " " + b);
}
}
- A [computing b] given B Correct
- B [computing a] [computing b] given B
- C given B
- D [computing a] given B
Correct Answer: Option A
The lambda body runs only if get() is called – the idea behind Optional.orElseGet.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!