Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A class returns its internal array from a getter and stores the array passed to its constructor. A caller's later changes corrupt the object's state. What review comments do you make?

The class keeps a reference to an array that the caller still holds and hands its own array out to anyone who asks, so outside code can change the object's state without going through it. My review comments would be to copy the array in the constructor and in the getter (array.clone()), or to return an unmodifiable List instead, to replace any public static final array with a private one behind an accessor or List.of, and to watch for the same leak in records with array components, whose generated equals also compares arrays by reference.

Why this question is asked

Encapsulation means an object controls its own state: nobody can put it into an invalid state from the outside. Arrays break that quietly, because they are mutable and passed by reference, and the bug they cause shows up far from the line that introduced it. Interviewers ask this as a code review question because it tests whether we can spot the leak, explain it in terms a teammate understands, and propose a fix that fits the cost. In this answer, we will reproduce the corruption, explain why it happens, go through the fixes for the constructor and the getter, look at the public static final array and record traps, and decide what to do when the arrays are large.

1A Quick Recap: Arrays Are Shared by Reference

When we pass an array to a method or a constructor, Java copies the reference, not the array. The caller and the callee then hold two references to the same array object. The same happens when a getter returns an array field: the caller gets a reference to the very array the object uses internally.

Because arrays are mutable, anyone holding a reference can change the elements. There is no way to make the contents of a Java array read-only. The final keyword on the field only stops the field from pointing to a different array; it does nothing to stop changes to the elements.

2Reproducing the Corruption

Here is the kind of class under review. A schedule keeps the opening hours for seven days and checks them in the constructor.

Java
public final class OpeningHours {
private final int[] hoursPerDay; // 7 values, each 0..24
public OpeningHours(int[] hours) {
if (hours.length != 7) throw new IllegalArgumentException("need 7 days");
for (int h : hours) if (h < 0 || h > 24) throw new IllegalArgumentException("bad hours " + h);
this.hoursPerDay = hours; // stores the caller's array
}
public int[] getHoursPerDay() { return hoursPerDay; } // hands out the internal array
}
int[] input = {8, 8, 8, 8, 8, 4, 0};
OpeningHours oh = new OpeningHours(input); // validated: all fine
input[6] = 99; // caller reuses its array later
System.out.println(oh.getHoursPerDay()[6]); // 99: the validated state is gone
oh.getHoursPerDay()[0] = -5; // any reader can write too
System.out.println(oh.getHoursPerDay()[0]); // -5
Step throughTwo ways the internal array leaks
CallerOpeningHoursint[] array
new OpeningHours(input)
store the same reference
input[6] = 99: changes the object's state
getHoursPerDay()
returns the internal reference
result[0] = -5: changes it again

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

Both the stored argument and the returned field point at one shared array.

Notice that the constructor's validation ran and passed, yet a moment later the object holds 99 and -5, values it would have rejected. The class is declared final with a final field, so it looks immutable, but its state is only as safe as every piece of code that ever got a reference to that array.

3Fix 1: Copy In, Copy Out

The standard fix is a defensive copy on the way in and on the way out. In the constructor we copy first and then validate the copy. In the getter we return a copy.

Java
public OpeningHours(int[] hours) {
int[] copy = hours.clone(); // copy first
if (copy.length != 7) throw new IllegalArgumentException("need 7 days");
for (int h : copy) if (h < 0 || h > 24) throw new IllegalArgumentException("bad hours " + h);
this.hoursPerDay = copy; // the caller has no reference to this array
}
public int[] getHoursPerDay() { return hoursPerDay.clone(); }
public int hoursOn(int day) { return hoursPerDay[day]; } // often all callers need
input[6] = 99;
System.out.println(oh.getHoursPerDay()[6]); // 0: unaffected

The order in the constructor matters. If we validated the caller's array and then copied it, another thread could change the array between the check and the copy, and we would store values that were never validated. Copying first means we validate exactly what we keep.

It is also worth asking whether callers need the whole array at all. A method like hoursOn(day) answers the usual question without copying anything.

4Fix 2: Return an Unmodifiable List

If callers need to read the whole collection, we can expose a read-only List instead of an array. For object arrays, Collections.unmodifiableList(Arrays.asList(array)) gives a view with no copy. For primitive data we pay a boxing cost once, which is fine for small arrays.

Java
private final List<Integer> hours; // built once in the constructor
// this.hours = Arrays.stream(copy).boxed().toList(); // unmodifiable
public List<Integer> hours() { return hours; }
oh.hours().set(0, -5); // throws UnsupportedOperationException

But there is a catch with views: Collections.unmodifiableList over our internal array blocks writes through the list, yet we can still change the array internally and readers will see it. That is fine when the object owns the array and never changes it, which is the case for an immutable class.

5The Public static final Array Trap

A related comment applies to constants. A field like public static final String[] VALID_CODES = {"A", "B"}; looks like a constant, but any code in the application can write VALID_CODES[0] = "X" and change it for everyone. The final keyword only freezes the reference.

Java
// Before: looks constant, is not
public static final String[] VALID_CODES = {"A", "B"};
// After, option 1: an immutable list
public static final List<String> VALID_CODES = List.of("A", "B");
// After, option 2: keep the array private and hand out copies
private static final String[] CODES = {"A", "B"};
public static String[] validCodes() { return CODES.clone(); }

List.of is usually the better choice: it cannot be changed, it is cheap to share, and readers see the intent. Static analysis tools such as SpotBugs flag mutable public static arrays, so this is also an easy rule to enforce in the build.

6Records With Array Components

Records feel safe because they are designed for immutable data, but a record does not copy its components. A record OpeningHours(int[] hours) stores the caller's array and its accessor hours() returns it, so it has exactly the same leak. Its generated equals also compares the array with reference equality, so two records with identical contents are not equal, and its toString prints something like [I@1b6d3586 instead of the values.

Java
record Hours(int[] values) {
Hours { values = values.clone(); } // compact constructor: copy in
@Override public int[] values() { return values.clone(); } // copy out
@Override public boolean equals(Object o) { return o instanceof Hours h && Arrays.equals(values, h.values); }
@Override public int hashCode() { return Arrays.hashCode(values); }
@Override public String toString() { return "Hours" + Arrays.toString(values); }
}
System.out.println(new Hours(new int[]{1}).equals(new Hours(new int[]{1}))); // true now (false without the override)

Once we override all of that, the record has lost most of its brevity, which is a strong hint that a List<Integer> component would be a better fit.

7When the Arrays Are Large

Copying seven ints costs nothing measurable. Copying a 50 MB array on every getter call in a hot path does. For large data we avoid repeated copies by giving out a read-only wrapper: a small class that holds the array privately and offers get(i), length() and bulk methods such as copyInto(int[] dest), or a read-only java.nio buffer such as IntBuffer.wrap(array).asReadOnlyBuffer(). Callers can read everything, nobody outside can write, and we copy only when a caller explicitly asks for its own array.

8Follow-up questions

Is clone() good enough for an array of mutable objects?

Only partly. The clone stops callers from replacing elements, but the element objects are still shared, so a caller can still change a Date or a StringBuilder inside. For mutable elements we either copy each element or, better, make the element type immutable, for example LocalDate instead of Date.

Why not just document that callers must not modify the array?

Because the bug appears far away from the mistake and is very hard to trace, and documentation does not stop a caller who reuses a buffer by accident. A defensive copy makes the class correct no matter what callers do, which is the whole point of encapsulation.

Does making the field final help?

It helps a little: the object can never be switched to a different array. But it does not protect the elements at all, so a final array field still needs defensive copies or a read-only wrapper.

9Conclusion

In this answer, we saw that storing a caller's array and returning an internal array both share one mutable object with the outside world, which lets callers change validated state without the class knowing. The review comments are to copy in the constructor before validating, to copy in the getter or return an unmodifiable List, to replace public static final arrays with List.of or a private array behind an accessor, and to remember that records with array components leak the same way and compare arrays by reference in equals. For large arrays, a read-only wrapper avoids repeated copies.

What to say in the interviewAbout 90 seconds aloud

Open with

My main comment would be that arrays are mutable and passed by reference, so this class does not really own its state. The constructor stores the caller's array, so when the caller reuses that array later, it changes our object, even after validation passed.

Then, if they want more

The getter returns the internal array, so any reader can write into it. Making the field final does not help, because final freezes the reference, not the elements.

The fix is to copy defensively in both places: in the constructor I clone first and then validate the copy, so nothing can change between the check and the store, and in the getter I return a clone, or better, return an unmodifiable List or offer a method like hoursOn(day) so callers rarely need the whole array.

I would also flag any public static final array, since anyone can change its elements; List.of or a private array with an accessor that copies fixes that.

If the code uses records, a record with an array component has the same leak, and its generated equals compares the array by reference, so two records with the same values are not equal; there I would use a List component instead.

And if the arrays are large and on a hot path, I would expose a read-only wrapper rather than copying on every call.

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 "A class returns its internal array from a getter and stores the array passed to its...": https://scrivio-interview-library.netlify.app/java/arrays/c47b638b96/