Card 06/ 10
All 10 cards
ExampleDifficulty: Intermediate1 min
A Method That Hands You a Different Order
The same call site, the same types, one word different inside the method. This time the caller's list comes back untouched.
static void replaceOrder(List<String> lines) {
lines = new ArrayList<>(List.of("refund"));
}
List<String> order = new ArrayList<>(List.of("book", "pen"));
replaceOrder(order);
System.out.println(order);[book, pen]Line 2 created a new list and pointed lines at it. lines is the method's own variable, so the only arrow that moved was the method's, and it stopped pointing at the caller's list before doing anything to it.
Put this beside the previous method and the shared fact comes out: both received a copy of the address, and the difference is only whether they followed the copy or overwrote it. Following it reaches the caller's object. Overwriting it reaches nothing.
That is the whole of pass-by-value in Java, and it is why "Java passes objects by reference" is a sentence worth unlearning. If it were true, line 2 would have replaced the caller's list.