Bird
0
0

What will be the output of this Java code snippet implementing Memento pattern?

medium📝 Analysis Q5 of 15
LLD - Behavioral Design Patterns — Part 2
What will be the output of this Java code snippet implementing Memento pattern?
record Memento(String state) {}

class Originator {
    private String state;
    public void setState(String state) { this.state = state; }
    public Memento save() { return new Memento(state); }
    public void restore(Memento m) { this.state = m.state(); }
    public String getState() { return state; }
}

Originator originator = new Originator();
originator.setState("A");
Memento m1 = originator.save();
originator.setState("B");
originator.restore(m1);
System.out.println(originator.getState());
AB
BA
Cnull
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Follow state changes in Originator

    State is set to "A", saved in Memento m1, then changed to "B".
  2. Step 2: Restore state from Memento and print

    Restoring from m1 sets state back to "A". Printing outputs "A".
  3. Final Answer:

    A -> Option B
  4. Quick Check:

    Restore resets state to saved snapshot [OK]
Quick Trick: Restore always reverts to saved snapshot [OK]
Common Mistakes:
MISTAKES
  • Expecting print to show last set state
  • Confusing record usage with error
  • Assuming null output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes