LearnFrenzy
Sign in Take a free test

Lambda Expressions · Predict the Output · Question 12

A method that returns a lambda Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.function.IntUnaryOperator;

public class Main {
    static IntUnaryOperator adder(int n) { return x -> x + n; }
    static IntUnaryOperator times(int n) { return x -> x * n; }

    public static void main(String[] args) {
        IntUnaryOperator add5 = adder(5), triple = times(3);
        IntUnaryOperator f = add5.andThen(triple).andThen(adder(-1));
        System.out.println(add5.applyAsInt(10) + " " + triple.applyAsInt(10) + " " + f.applyAsInt(2) + " " + IntUnaryOperator.identity().compose(triple).applyAsInt(4));
    }
}
  • A 15 30 20 12 Correct
  • B 15 30 21 12
  • C 15 30 20 4
  • D 15 30 9 12
Correct Answer: Option A

(2 + 5) × 3 − 1 = 20. Each returned lambda remembers the n it was created with.

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