Card 05/ 10

ExampleDifficulty: Intermediate1 min

Pass-by-Value Example: A Method That Adds a Line to Your Order

The method follows its copy of the address, and the caller's list grows.

Java passes a copy of the reference, which is pass-by-value: a method that calls a changing method, such as add, on an object it was passed changes that object, and the caller sees the change, because both hold the address of the same object. An order with two lines on it, handed to a method that adds delivery:

java
static void addDelivery(List<String> lines) {
    lines.add("delivery");
}

List<String> order = new ArrayList<>(List.of("book", "pen"));
addDelivery(order);
System.out.println(order);
text
[book, pen, delivery]

The caller's list has three items. lines and order are two different variables, and both hold the same address, so lines.add(...) followed the address and changed the one list that is there.

The method never touched order. It touched what order points at.

The caller had no say in this. Anyone who hands a list to addDelivery should expect it back changed, and if they need the original, they pass a copy: addDelivery(new ArrayList<>(order)).