AI Hints
Home›Java Tutorial›Overloading, Scope and Pass by Value
Java · Lesson 60 of 120

Pass by Value

Copies, not originals.

⏱ 2 min read▶ Video at 1:14:50🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

When you pass a value into a method, Java passes a copy. Changing the copy doesn't change the original. But arrays and objects have a twist.

  • Java passes a copy
  • Original unchanged
  • But arrays have a twist

A copy, and a shared array

Add ten gets a copy of x. It changes its copy, but x itself stays five. An array variable holds a reference, like an address. The method gets a copy of that address, which still points to the same array. So changes to the array's boxes are seen by everyone. Run it. X is still five. But the array is now eleven, twelve, thirteen.

Main.javajava
import java.util.Arrays;
public class Main {
    static void addTen(int n) {
        n = n + 10;
    }

    static void addTenToAll(int[] arr) {
        for (int i = 0; i < arr.length; i++) arr[i] += 10;
    }

    public static void main(String[] args) {
        int x = 5;
        addTen(x);
        System.out.println("x is still " + x);
        int[] nums = {1, 2, 3};
        addTenToAll(nums);
        System.out.println("nums is now " + Arrays.toString(nums));
    }
}
Output
x is still 5
nums is now [11, 12, 13]

Primitives and references

For primitives, like int and double, the method gets a copy of the value. For arrays and objects, it gets a copy of the reference. So it can change what the reference points to.

Primitives

  • int, double, booleanCopy of the valueOriginal safe

Arrays and objects

  • int[], String, your classesCopy of the referenceSame object inside

Summary

Java always passes copies. For primitives, that's a copy of the value. For arrays and objects, it's a copy of the reference, so the contents can change. Next, methods that call themselves.

Key takeaways
  • Copies always
  • Primitives: safe
  • Arrays: shared contents
Next up: Recursion — a method that calls itself