Polymorphism

AP Computer Science A· difficulty 3/5

ArrayList<Object> list = new ArrayList<Object>();
list.add("hello");
list.add(42);
list.add(3.14);
int count = 0;
for (int i = 0; i < list.size(); i++) {
    if (list.get(i) instanceof String) count++;
}
System.out.print(count);

What is printed?

  • A

    2

  • B

    0

  • C

    3

  • D

    1

    check_circle

Explanation

Only "hello" is a String. 42 autoboxes to Integer, 3.14 to Double. So instanceof String is true exactly once.

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

Related questions