Core Java Fundamentals ยท Methods

Pass by Value: Primitives vs References

Java always copies the argument. For an int that is the number; for an array it is the reference, so the method can change the array itself.

PassByValueDemo.java

public class PassByValueDemo {
    static void addTen(int n) {
        n = n + 10;
    }

    static void addItem(int[] items) {
        items[0] = items[0] + 10;
    }

    public static void main(String[] args) {
        int score = 5;
        addTen(score);
        int[] scores = {5, 6};
        addItem(scores);
        System.out.println(score + " " + scores[0]);
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). score is created on the stack with the value 5.
  2. addTen(score): Java copies the value 5 into the parameter n.
  3. n becomes 15, but n is only the method's own copy.
  4. addTen ends; its copy is gone and score is still 5.
  5. The value it returned, [5, 6], is stored in scores.
  6. addItem(scores): the copy is of the reference, so items points to the same array as scores.
  7. Changing items[0] changes the one shared array.
  8. addItem() has finished, so its variables are gone.
  9. It prints 5 15.
  10. score is still 5, but scores[0] is 15. Java copies values; for objects, the value is a reference to the same object.