Skip to the workspace
Pebellslearn by building
Object-Oriented Principles  ›  Capstone Project

Pass by Value: What a Method Really Receives

Pass by Value / Pass by Reference 14 minJava 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.

java / Pass by Value: What a Method Really Receives

Explore each scene at your own pace.

01 · The rule

The rule

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 250

People 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.