Java OCA OCP Practice Question 2396

Question

What happens when you try to compile and execute the following class with Java 7? (Choose all that apply.)

class Main {//from w  w  w  .jav  a  2  s  . c o  m
   public static void main(String args[]) {
       ArrayList list = new ArrayList();
       list.add("ABCD");
       list.add(1);
       list.add(new Thread());

       for (Object obj:list) System.out.println(obj);
   }
}
  • a Class Main fails to compile with Java 7.
  • b Class Main compiles with a compilation warning when compiled with Java 7.
  • c Class Main iterates though all the objects of the list and prints their values as returned by their method toString().
  • d Class Main prints the first list value and throws a ClassCastException while trying to print the second list element.


b, c

Note

The code executes, printing all the values of the objects added to the List.

Method toString() is implicitly called when you try to print the value of an object.

Using a raw type of interface is allowed post-introduction of generics.

This is allowed for backward compatibility with non generics code.

But all uses of the add methods with List's raw type will compile with the following compilation warning:.

warning: [unchecked] unchecked call to add(E) as a member of the raw type
ArrayList
   list.add("ABCD");
       ^
where E is a type-variable:

E extends Object declared in class ArrayList



PreviousNext

Related