LearnFrenzy
Sign in Take a free test

Lambda Expressions · Predict the Output · Question 18

A recursive lambda through a field Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following Java program?

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

public class Main {
    // A lambda cannot refer to its own local variable while it is being declared,
    // but it can call itself through a static field.
    static IntUnaryOperator fact;
    static IntUnaryOperator fib;

    public static void main(String[] args) {
        fact = n -> n <= 1 ? 1 : n * fact.applyAsInt(n - 1);
        fib = n -> n < 2 ? n : fib.applyAsInt(n - 1) + fib.applyAsInt(n - 2);
        System.out.println(fact.applyAsInt(6) + " " + fib.applyAsInt(10));
    }
}
  • A 720 55 Correct
  • B 120 55
  • C 720 89
  • D Compilation error
Correct Answer: Option A

The field is read when the lambda runs, by which time it has been assigned.

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