Java OCA OCP Practice Question 1871

Question

Which statement about the program is true?.


class MyClass {}// ww w  . j  a  v  a  2  s . c  om

class MyClass2 extends MyClass {}

// Filename: MyClass.java
public class MyClass {
  public static void main(String[] args) {
    MyClass[] arrMyClass;
    MyClass2[] arrMyClass2;

    arrMyClass = new MyClass[10];
    arrMyClass2 = new MyClass2[20];
    arrMyClass = arrMyClass2;       // (1)
    arrMyClass2 = (MyClass2[]) arrMyClass; // (2)
    arrMyClass = new MyClass[10];
    arrMyClass2 = (MyClass2[]) arrMyClass; // (3)
  }
}

Select the one correct answer.

  • (a) The program will fail to compile because of the assignment at (1).
  • (b) The program will throw a java.lang.ClassCastException in the assignment at (2), when run.
  • (c) The program will throw a java.lang.ClassCastException in the assignment at (3), when run.
  • (d) The program will compile and run without errors, even if the cast operator (MyClass2[]) in the statements at (2) and (3) is removed.
  • (e) The program will compile and run without errors, but will not do so if the cast operator (MyClass2[]) in statements at (2) and (3) is removed.


(c)

Note

The program will throw a java.lang.ClassCastException in the assignment at (3), when run.

The statement at (1) will compile, since the assignment is done from a subclass reference to a superclass reference.

The cast at (2) assures the compiler that arrMyClass will refer to an object that can be referenced by arrMyClass2.

This will work when run, since arrMyClass will refer to an object of type MyClass2[].

The cast at (3) will also assure the compiler that arrMyClass will refer to an object that can be referenced by arrMyClass2.

This will not work when run, since arrMyClass will refer to an object of type MyClass[].




PreviousNext

Related