Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Find the bug and fix it:

Java
final class Period {
private final Date start, end;
Period(Date s, Date e) {
if (s.after(e)) throw new IllegalArgumentException();
start = s;
end = e;
}
Date start() {
return start;
}
}

Period looks immutable because its fields are final, but java.util.Date is mutable, so the caller can change start or end after construction through its own reference, or through the Date returned by start(), and break the rule that start is not after end. The fix is to copy the inputs first with new Date(s.getTime()), then validate the copies, and to return copies from the getters; better still, use java.time.Instant, which is immutable. We avoid clone() on the parameters because a malicious subclass of Date could return anything.

Why this question is asked

This is a classic code-review exercise, and the bug it shows still appears in real code wherever a mutable object is stored in an object that claims to be immutable. Interviewers like it because a good answer covers three separate attacks, shows the order of operations matters, and ends with the modern fix. In this answer, we will recap why Date is the problem, break the class in two ways, fix it with defensive copies, see why we validate after copying and avoid clone(), and finish with the java.time version.

1A Quick Recap: The Problem With Date

java.util.Date represents a point in time as milliseconds since 1970, but unlike the newer java.time types it is mutable: setTime and several deprecated setters change the object in place. When a class stores a Date that someone else also holds, that someone can change our state without calling any of our methods.

The Period class marks its fields final, but final only means the field always refers to the same Date object. The object itself can still change. So the invariant the constructor checks, that start is not after end, can be broken at any moment after the check.

2Breaking the Class in Two Ways

The first attack uses the reference the caller passed in. The second uses the reference the getter hands out.

Java
Date s = new Date(); // now
Date e = new Date(s.getTime() + 1000); // one second later
Period p = new Period(s, e); // passes the check
e.setTime(0); // attack 1: change the caller's Date
System.out.println(p.start().after(p.end())); // true: end is now 1970, before start
Period q = new Period(new Date(), new Date(System.currentTimeMillis() + 1000));
q.start().setTime(Long.MAX_VALUE); // attack 2: change through the getter
System.out.println(q.start().after(q.end())); // true again

Neither attack calls a method on Period that changes it, yet both leave a Period that violates its own rule. Code that later trusts the Period, for example to compute a duration or check overlaps, now gets nonsense results.

3Fix: Copy First, Then Validate, and Copy on the Way Out

The fix has three parts. We copy each incoming Date into a new Date that only Period can reach. We validate the copies, not the parameters. And getters return a new copy each time, so callers never receive our internal objects.

Java
public final class Period {
private final Date start, end;
public Period(Date s, Date e) {
this.start = new Date(s.getTime()); // copy first
this.end = new Date(e.getTime());
if (this.start.after(this.end)) { // then check the copies
throw new IllegalArgumentException(this.start + " after " + this.end);
}
}
public Date start() { return new Date(start.getTime()); } // copy out
public Date end() { return new Date(end.getTime()); }
}
Date s = new Date(), e = new Date(s.getTime() + 1000);
Period p = new Period(s, e);
e.setTime(0); // only the caller's Date changes
p.start().setTime(Long.MAX_VALUE); // only the returned copy changes
System.out.println(p.start().after(p.end())); // false: the invariant holds

Notice that s.getTime() also acts as a null check: a null argument throws NullPointerException before any field is assigned. And the class is final, so a subclass cannot override start() to return the internal Date.

4Why Validate After Copying

The order of the first lines matters. Suppose we checked s.after(e) first and copied afterwards. Between the check and the copy, another thread holding the caller's Date objects could change them. We would then copy values that were never checked, and the Period would hold an invalid range even though the check passed. This is called a check-then-act race, or time-of-check to time-of-use.

Step throughValidate before copying: the race
ConstructorCaller's Date eOther thread
check: s.after(e)? no
e.setTime(0)
copy e.getTime() = 0
stores an end before the start

4 messages in order. Play them, or step through them one at a time.

Copying first means the values we check are the values we keep; no other thread can reach the copies.

5Why Not clone()?

It is tempting to write this.start = (Date) s.clone(). But Date is not final, so the argument could be an instance of a subclass written by an attacker or just by careless code. That subclass can override clone() to return itself, or to keep a reference to the returned object and change it later. By calling new Date(s.getTime()), we create an object of exactly the Date class with only the time value taken from the argument, so no subclass code ends up inside our Period.

Inside the getters, clone() would be safe, because we know our own fields are plain Date objects that we created. Using the same new Date(...) style in both places simply keeps the code consistent.

6The Modern Fix: Use Instant

All of this effort exists only because Date is mutable. java.time.Instant represents the same thing, a point on the timeline, and it is immutable and final. With Instant, no copies are needed, and a record gives us the whole class in a few lines.

Java
public record Period(Instant start, Instant end) {
public Period {
Objects.requireNonNull(start, "start");
Objects.requireNonNull(end, "end");
if (start.isAfter(end)) throw new IllegalArgumentException(start + " after " + end);
}
public Duration length() { return Duration.between(start, end); }
}
Period p = new Period(Instant.now(), Instant.now().plusSeconds(60));
System.out.println(p.length()); // PT1M (or a few milliseconds more)

Callers that still have Date values can convert at the boundary with date.toInstant(), and that conversion is itself a copy. New code should not use Date in its API at all.

7Follow-up questions

Why validate after copying rather than before?

Because the caller still holds the original Date objects, and another thread can change them at any moment. If we validated the originals and then copied, the values could change between the two steps, and we would keep values that were never checked. Our copies are private from the moment they exist, so once validated, they stay valid.

Is returning a copy from the getter expensive?

Each call allocates a small Date object, which is cheap on a modern JVM, and often removed by escape analysis when the caller only reads it. If it shows up in a profile, the better fix is to switch to Instant, which needs no copies at all, rather than to stop copying.

Would making the fields private and final but returning Date be enough if callers promise not to change them?

No. Immutability is a guarantee, not a promise. Any caller, including future code written by someone who never saw the promise, can call setTime. Defensive copying, or an immutable type, turns the promise into something the compiler and the runtime enforce.

8Conclusion

In this answer, we saw that Period is not immutable because Date is mutable: callers can change the original arguments or the objects returned by the getters and break the start-before-end rule. We fixed it by copying the inputs with new Date(getTime()), validating the copies to avoid a check-then-change race, and returning copies from the getters. We avoid clone() on parameters because a subclass of Date can override it. The best fix is to use java.time.Instant, which is immutable, so a record with a validating compact constructor is all we need.

What to say in the interviewAbout 80 seconds aloud

Open with

The fields are final, but Date is mutable, so final only fixes the reference. There are two attacks: the caller can call setTime on the Date objects it passed in, and anyone can call setTime on the Date returned by start(), and either way the period can end before it starts even though the constructor checked it.

Then, if they want more

I would fix it by copying both arguments in the constructor with new Date(s.getTime()), validating the copies rather than the parameters, and returning a new Date from each getter.

The order matters: if I validated first and copied afterwards, another thread could change the caller's Date between the check and the copy, so I would store values that were never checked.

I would also avoid s.clone(), because Date is not final and the argument could be a subclass whose clone returns itself or keeps a reference; new Date(getTime()) always gives me a plain Date. The class is already final, which stops a subclass from leaking the fields.

In new code I would not use Date at all: java.time.Instant is immutable, so a record Period(Instant start, Instant end) with a compact constructor that checks start is not after end needs no copying anywhere.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the bug and fix it:": https://scrivio-interview-library.netlify.app/java/immutability/d53ffe4217/