Traversing ArrayLists

AP Computer Science A· difficulty 4/5

import java.util.ArrayList;
public static int run() {
    ArrayList<Integer> a = new ArrayList<>();
    for (int i = 1; i <= 5; i++) a.add(i);
    ArrayList<Integer> b = a;
    b.set(0, 99);
    return a.get(0) + b.get(0);
}
// Call: System.out.println(run());

What is printed?

  • A

    2

  • B

    99

  • C

    198

    check_circle
  • D

    100

Explanation

a and b reference the same list. Both get(0) = 99. Sum = 198.

Want 10 more like this — adaptive to your weak spots?

Related questions