Search code examples
javaarraysobjectjvminstantiation

Which constructor is called while making the array of a custom data type?


class Student
{
    private String name;
    private int rollno;
}

public void someMethod()
{
    Student s = new Student[2];  // line 1
    // do something here
}

Is a constructor called in line 1 while instantiating the objects for the array? If yes and it is the default one, let's say we write a parametrized constructor from our side. Since, the default constructor provided by JVM no longer exists, what gets called now? It would be really helpful if someone could explain the exact steps that take place while statement in line 1 is being executed. Thanks.


Solution

  • Is a constructor called in line 1 while instantiating the objects for the array

    No. The Student constructor is not called. It only allocates an array object of type Student of size 2. All the elements in the array will be initialized to null.

    You'll have to create a new Student object when you assign to the array elements. For that you may be calling the Student class constructors.

    s[0] = new Student();
    

    Currently, the Student class has only the default constructor.