CodeBlanks Logo Icon CodeBlanks

Object parameters

Learn to pass object references.

Object parameters

When you pass an object (say an ArrayList or an array) to a method, you actually pass a copy of the reference. The method reaches the same object.

static void addOne(ArrayList<Integer> list) {
  list.add(1);
}
ArrayList<Integer> xs = new ArrayList<>();
addOne(xs);
// xs: [1]

When the method calls list.add(1), the outer xs changes too. Because both point to the same object. If you assign a new list (list = new ArrayList<>()), the outside is not affected.

Reassigning a reference does not affect the outside

If you reassign the parameter to a new object inside the method, the outside object does not change. Only the method's own reference starts pointing to the new object.

static void reset(ArrayList<Integer> list) {
  list = new ArrayList<>();  // does not affect outside
}
ArrayList<Integer> xs = new ArrayList<>();
xs.add(9);
reset(xs);
// xs is still [9]

So changing the contents of the object affects the outside; reassigning the reference does not.

Practice Add a value to the list

Define a static void method called addItem; parameters ArrayList<Integer> list, int value. The body should call list.add(value). In main, create a list, call addItem(list, 7), and print the list.

Starter code

Main.java
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();
    // Call the addItem method with 7
    // Print the list
  }
  // Define the addItem method here
}

Sample solution

Main.java
static void addItem(ArrayList<Integer> list, int value) {
  list.add(value);
}
// inside main:
addItem(list, 7);
System.out.println(list);

Expected output

[7]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: add to the list

Question
static void addOne(ArrayList<Integer> list) {
  list.____(1);
}
Answer
static void addOne(ArrayList<Integer> list) {
  list.add(1);
}

Explanation: list.add(1) changes the list both in the method and outside.

2 Match scenario to result

Term Meaning
list.add(1) Outer list changes
list = new ArrayList<>() Outer list stays the same
list.clear() Outer list is emptied
int n = 5; zero(n); n does not change

3 What happens if you pass an ArrayList to a method and call list.add(...) inside?

  • The outer list changes
  • It causes a compile error
  • The outer list does not change Correct answer
  • A new copy is created

Explanation: The reference copy points to the same object; add changes the outside.

All lessons in Beginner