LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 17

A local class capturing a local variable Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    interface Greeting { String say(String name); }

    static Greeting make(String prefix) {
        int times = 2;                               // effectively final
        class Repeater implements Greeting {
            public String say(String name) { return (prefix + name + " ").repeat(times).trim(); }
        }
        return new Repeater();
    }

    public static void main(String[] args) {
        Greeting g = make("Hi ");
        System.out.println(g.say("Asha") + " | " + make("Bye ").say("Ravi"));
    }
}
  • A Hi Asha Hi Asha | Bye Ravi Bye Ravi Correct
  • B Hi Asha | Bye Ravi
  • C Hi Asha Hi Asha | Hi Ravi Hi Ravi
  • D Compilation error
Correct Answer: Option A

Local and anonymous classes (like lambdas) capture effectively final local variables; each object keeps its own captured values.

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