Given the following code, which of the numbered lines should be commented, to have the code compile and run successfully? Select the appropriate line numbers.

class Parent { }
class Child extends Parent { }
class Child2 extends Parent { }  

public class АrrауTest {
    public static void main(String[] args) {
        Parent[] arr1 = new Child[3];
        arr1[0] = new Parent(); //1
        arr1[1] = new Child();  //2
        arr1[2] = new Child2(); //3
        arr1[3] = new Child();  //4

        Child2[] arr2 = {new Child2(), new Child2(), new Child2()};

    public static void add(Parent[] arr) {
        arr[0] = new Parent(); //5
        arr[1] = new Child();  //6
        arr[2] = new Child2(); //7
        arr[3] = new Child2(); //8
Lines 4 and 8 will throw an ArrayIndexOutOfBoundsException (the last index for an array of size 3 is 2) Lines 1 and 5 will throw an ArrayStoreException, since an array of a subclass type can not store an object of superclass type. (The opposite would work though). Lines 3 and 6 will also throw an ArrayStoreException, since Child and Child2 class types are not each others subtypes.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback