Searching

AP Computer Science A· difficulty 3/5

ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(8);
list.add(3);
list.add(8);
int idx = -1;
for (int i = 0; i < list.size(); i++) {
    if (list.get(i) == 8) {
        idx = i;
        break;
    }
}
System.out.println(idx);

What is printed?

  • A

    3

  • B

    1

    check_circle
  • C

    0

  • D

    -1

Explanation

The first occurrence of 8 is at index 1, and break exits before finding the second one.

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

Related questions