Java OCA OCP Practice Question 2616

Question

Consider the following program:

class Main {/*  w w  w.  j a  va  2s  .co  m*/
        static <E> E cast(Object item) {                // ERROR1
                return (E) item;
        }
        public static void main(String []args) {
                Object o1 = 10;
                int i = 10;
                Integer anInteger = 10;

                Integer i1 = cast(o1);                  // ERROR2
                Integer i2 = cast(i);                   // ERROR3
                Integer i3 = cast(10);                  // ERROR4
                Integer i4 = cast(anInteger);           // ERROR5

                System.out.printf("i1 = %d, i2 = %d, i3 = %d, i4 = %d", i1, i2, i3, i4);
        }
}

Which one of the following options correctly describes the behavior of this program?

  • a) This program will result in a compiler error in the line marked with the comment ERROR1.
  • b) This program will result in a compiler error in the line marked with the comment ERROR2.
  • c) This program will result in a compiler error in the line marked with the comment ERROR3.
  • d) This program will result in a compiler error in the line marked with the comment ERROR4.
  • e) This program will result in a compiler error in the line marked with the comment ERROR5.
  • f) When executed, this program will print the following: i1 = 10, i2 = 10, i3 = 10, i4 = 10.


f)

Note

This is a correct implementation of generic method cast for casting between the types.

Note that you'll get an "unchecked cast" warning (not an error) in the definition of the cast method since an unsafe explicit conversion is performed from Object to type E.




PreviousNext

Related