Question 17
Back to Exercise
What is the output of the following Java program?
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!