LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 10

Leaking a mutable java.util.Date Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.Date;

class Booking {
    private final Date leaky;
    private final Date safe;
    Booking(Date d) { leaky = d; safe = new Date(d.getTime()); }
    Date getLeaky() { return leaky; }
    Date getSafe() { return new Date(safe.getTime()); }
}

public class Main {
    public static void main(String[] args) {
        Date d = new Date(1_000);
        Booking b = new Booking(d);
        d.setTime(5_000);
        b.getSafe().setTime(9_000);
        System.out.println(b.getLeaky().getTime() + " " + b.getSafe().getTime());
    }
}
  • A 5000 1000 Correct
  • B 1000 1000
  • C 5000 9000
  • D 1000 9000
Correct Answer: Option A

Date is mutable, so the stored reference changes with the caller's object; copies in and out keep safe intact. (Prefer the immutable java.time types.)

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