nerdexam
Oracle

1Z0-808 · Question #82

Given the code fragment: 1. ArrayList<Integer> list = new ArrayList<>(); 2. list.add(1001); 3. list.add(1002); 4. System.out.println(list.get(list.size())); What is the result?

The correct answer is C. An exception is thrown at run time due to error on line 4. Option C is correct because list.size() returns 2 (there are two elements), but ArrayList uses zero-based indexing, meaning valid indices are 0 and 1. Calling list.get(2) attempts to access a non-existent element, throwing an IndexOutOfBoundsException at runtime on line 4. Why…

Working with Selected Classes from the Java API

Question

Given the code fragment:
  1. ArrayList<Integer> list = new ArrayList<>();
  2. list.add(1001);
  3. list.add(1002);
  4. System.out.println(list.get(list.size())); What is the result?

Options

  • ACompilation fails due to an error on line 1.
  • BAn exception is thrown at run time due to error on line 3
  • CAn exception is thrown at run time due to error on line 4
  • D1002

How the community answered

(55 responses)
  • A
    9% (5)
  • B
    5% (3)
  • C
    84% (46)
  • D
    2% (1)

Explanation

Option C is correct because list.size() returns 2 (there are two elements), but ArrayList uses zero-based indexing, meaning valid indices are 0 and 1. Calling list.get(2) attempts to access a non-existent element, throwing an IndexOutOfBoundsException at runtime on line 4.

Why the distractors are wrong:

  • A is wrong - line 1 is perfectly valid; the diamond operator <> has been supported since Java 7.
  • B is wrong - line 3 adds 1002 to the list without any issue; ArrayList.add() does not throw an exception here.
  • D is wrong - to get 1002 (the last element), you'd need list.get(list.size() - 1), i.e., index 1.

Memory tip: Think of it as a "fencepost" rule - a list of n elements has indices 0 through n-1. size() always equals the count, which is always one past the last valid index. When you see list.get(list.size()), spot the missing - 1 immediately.

Topics

#ArrayList indexing#bounds checking#size() method#IndexOutOfBoundsException

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice