Card 06/ 10
Pass-by-Value Example: A Method That Reassigns Its Parameter
The same call, one word different inside the method, and the caller's list comes back untouched.
A method that assigns a new object to its own parameter changes only its copy of the address, so the caller's variable still points at the original. A method that receives the caller's order list and assigns a brand new list to its own parameter, instead of adding to the list it was given:
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 variable that changed was the method's own lines, and it stopped pointing at the caller's list before doing anything to it.
Put this beside a method that calls lines.add("delivery") on the same parameter, where the caller does see the change, 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 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.
← → move through sections and cards