Pass by Value: What a Method Really Receives
Java passes every argument by value, so a method gets a copy of a primitive or a copy of a reference that still points to the caller's object.
Compare changing a parameter with mutating the object its copied reference reaches.
Brew Bar's happy-hour method lowers a drink's price, and it works. The "add a free cup" method changes the cup count, and it does nothing. Both look almost identical. The difference is one of the most asked questions about Java, and it has a single answer.
The rule
Java always passes a copy; for objects, the copy is a reference.
When you call a method, each parameter receives a copy of the value in the caller's variable. Java has no other mode.
- For a primitive such as
int, the value is the number itself. The method gets its own copy of the number, so changing it cannot affect the caller. - For an object or array, the value in the variable is a reference, an arrow to the object. The method gets a copy of the arrow, which points at the same object.
That gives two opposite results:
static void addFreeCup(int cups) {
cups++; // changes the method's copy only
}
static void happyHour(Drink d) {
d.priceCents -= 50; // follows the arrow: the shared object changes
}
static void swapForTea(Drink d) {
d = new Drink("Tea", 150); // re-points the method's copy of the arrow only
}int cups = 2;
addFreeCup(cups); // cups is still 2
Drink latte = new Drink("Latte", 300);
happyHour(latte); // latte.priceCents is now 250
swapForTea(latte); // latte is still the Latte, at 250People sometimes say "objects are passed by reference". That is not quite right, as swapForTea proves: if the caller's variable itself were passed, reassigning d would change latte. It does not.
String looks like an exception but is not. Strings are immutable, so a method cannot change the object, and s = s + "!" only re-points the method's own copy.