Enhanced for Loop for Arrays

AP Computer Science A· difficulty 3/5

int[] a = {1, 2, 3};
for (int x : a) {
  x = x * 2;
}
System.out.println(a[0] + " " + a[1] + " " + a[2]);

What is printed?

  • A

    1 2 3

    check_circle
  • B

    2 4 6

  • C

    0 0 0

  • D

    Compilation error

Explanation

The for-each loop variable x is a copy of each element. Reassigning x does not modify the underlying array. To modify, you must use a standard for-loop with an index.

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

Related questions