Java OCA OCP Practice Question 2949

Question

Given:

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Main extends Shape {
   public static void main(String[] args) {
      final List<String> s = new ArrayList<String>();
      s.add("a");
      s.add("f");
      s.add("a");
      new Main().mutate(s);
      System.out.println(s);//from  w ww  .j  a v a 2 s  .co  m
   }

   List<String> mutate(List<String> s) {
      List<String> ms = s;
      ms.add("c");
      return s;
   }
}

class Shape {
   final void mutate(Set s) {
   }
}

What is the most likely result?

  • A. [a, f]
  • B. [a, f, a]
  • C. [a, f, c]
  • D. [a, f, a, c]
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


D is correct.

Note

The List is "final", but that doesn't mean its contents can't change.

Lists can contain duplicates, and mutate() gets a copy of the reference variable, so it's adding to the same List.

Shape's final mutate() isn't being overridden, it's being overloaded.




PreviousNext

Related