Java OCA OCP Practice Question 2212

Question

Which statements when inserted independently will throw an exception at runtime? (Choose two.)

ArrayDeque<Integer> d = new ArrayDeque<>(); 
d.offer(18); 
// INSERT CODE HERE 
  • A. d.peek(); d.peek();
  • B. d.poll(); d.poll();
  • C. d.pop(); d.pop();
  • D. d.remove(); d.remove();


C, D.

Note

Option A is incorrect because the peek() method returns the next value or null if there isn't one without changing the state of the queue.

In this example, both peek() calls return 18.

Option B is incorrect because the poll() method removes and returns the next value, returning null if there isn't one.

In this case, 18 and null are returned, respectively.

Options C and D are correct because both the pop() and remove() methods throw a NoSuchElementException when the queue is empty.

This means both return 18 for the first call and throw an exception for the second.




PreviousNext

Related