Card 09/ 10

ExerciseDifficulty: Intermediate1 min

Three Methods, One Object: What Does the Caller Hold

Three methods, each called once on the same starting list. Write down what the caller prints after each one before opening the reveal.

java
static void one(List<String> xs) { xs.add("x"); }
static void two(List<String> xs) { xs = new ArrayList<>(); xs.add("y"); }
static void three(List<String> xs) { xs.clear(); xs.add("z"); }

List<String> a = new ArrayList<>(List.of("start"));
one(a);
System.out.println(a);
What does the caller print after each of the three, starting from [start] each time?
Each method, what the caller sees, and why
MethodCaller printsWhy
one[start, x]Followed the address and changed the list
two[start]Pointed its own variable elsewhere, then changed something the caller cannot reach
three[z]Followed the address twice — emptied the caller's list, then added to it

The test to apply to any method is one question: does it use the reference, or does it assign to the variable holding it? Using it reaches the caller's object. Assigning to it reaches nothing.

three is the one worth pausing on. It is the most destructive of the three and the only one whose name gives no hint that it will empty what you handed it.