LearnFrenzy
Sign in Take a free test

Lambda Expressions · Predict the Output · Question 7

A Supplier is evaluated only when called Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links