Introduction to ArrayList

AP Computer Science A· difficulty 2/5

ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= 5; i++) list.add(i);
int s = 0;
for (int x : list) s += x;
System.out.println(s);

What is printed?

  • A

    Compile-time error

  • B

    5

  • C

    10

  • D

    15

    check_circle

Explanation

The loop adds 1, 2, 3, 4, 5 to the list. Summing them with the for-each loop gives 1+2+3+4+5 = 15. Autoboxing converts each int to an Integer when adding.

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

Related questions