Course outline · 0% complete

0/29 lessons0%

Course overview →

Scope and pass-by-value

lesson 4-3 · ~7 min · 12/29

What can a method actually change?

Sooner or later you will pass a variable into a method, watch the method "change" it, and find the original untouched — or the reverse: a method quietly modifies an array you never expected it to. Both surprises come from one rule, and misunderstanding it causes real bugs in real code reviews, so it is worth one focused lesson.

The rule: Java always passes a copy of the variable's value into the method. This is called pass-by-value, and Java has no other mode.

  • For a primitive (int, double, boolean...), the value is the number, so the method gets a copy of the number. Nothing the method does can touch the caller's variable.
  • For an object type (arrays, Strings, your classes), the value stored in the variable is a reference — the heap location from lesson 2-2. The method gets a copy of the reference, but both copies point at the same object. So the method cannot re-point your variable, yet it can modify the object your variable points at.

Code exercise · java

Run this. addBonus gets a copy of the int, so the caller's score stays 50. zeroFirst gets a copy of the array reference, but that copy points at the same array, so the change is visible to the caller.

Scope: where a name is alive

A variable's scope is the region of code where its name means something: from its declaration to the closing brace } of the block it was declared in. The rule exists so that names cannot collide across a large program — the i in one method and the i in another are strangers.

for (int i = 0; i < 3; i++) {
  int doubled = i * 2;   // born each pass
}
// i and doubled do not exist here — compile error if used

Two practical consequences:

  • A loop variable dies at the loop's }. Need the result afterwards? Declare it before the loop (the max pattern from lesson 3-3 did exactly this).
  • A method's parameters are local to that method. score inside addBonus above is a different variable from score in main, even though the names match — which is exactly why the copy rule felt surprising.

Quiz

A method receives an ArrayList<String> parameter (ArrayList is a resizable list you will meet properly in unit 7) and calls list.add("x") on it. What does the caller observe afterwards?

Code exercise · java

Your turn. Write static void doubleAll(int[] nums) that doubles every element in place using a classic for loop over the indexes. main calls it and prints each element — the output should be 6, 10, 16 on separate lines.