Writing Methods

AP Computer Science A· difficulty 4/5

public static void scale(int[] arr, int k) {
  for (int i = 0; i < arr.length; i++) {
    arr[i] *= k;
  }
}
public static void main(String[] args) {
  int[] a = {1, 2, 3};
  scale(a, 3);
  System.out.println(a[0]+" "+a[1]+" "+a[2]);
}

What is printed?

  • A

    Compilation error

  • B

    0 0 0

  • C

    1 2 3

  • D

    3 6 9

    check_circle

Explanation

The method modifies the underlying array via index. Because array references point to the same object, changes are visible to the caller: 1<em>3, 2</em>3, 3*3.

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

Related questions