Objects, statics, and mutation
Instance vs static ledgers, ArrayList removal shifts, and reference semantics under pass-by-value.
Object and static state. Instance fields belong to an object; static fields belong to the class โ one copy shared by every instance and every call. Traces go wrong when the two mix:
public class Counter {
private static int created = 0;
private int value;
public Counter(int v) { value = v; created++; }
public int bump() { value++; return value; }
}
After new Counter(5), new Counter(7), and c.bump() on the first:
value lives per-object (5โ6), created lives on the class (2). A
question asking "what is created after these calls" is testing whether
you keep the two ledgers separate.
ArrayList mutation adds its own trap: remove(i) shifts everything
after i left. A loop that removes while iterating forward skips the
element that slid into position i โ the classic trace answer is "one
element survived that you believe was removed."
Pass-by-value of references: a method can mutate the object its parameter points at (visible to the caller) but can never make the caller's variable point somewhere else. Traced precisely:
public static void scramble(int[] a, int[] b) {
a[0] = 100; // visible to caller
b = new int[9]; // local rebinding only
b[0] = 7; // lost
}