Hani Goc Hani Goc - 10 days ago 6
Java Question

Does any empty an array of a specific type holds object of that type or empty slots? (Garbage collector)

In the following example which I am trying to understand. They say (Core Java SCJP Quiz Questions (Google Play)) that 5 objects were created and 2 are for the Garbage collector.

When I tried to solve it. I came out with 3 objects and 1 for the garbage collector (It is wrong I know). The three objects are:


  1. College [] c = new College[3]
    ;

  2. c[0] = new College();

  3. College co = new College();







  • co= null
    is for the garbage collector.

  • c1 is just a reference.






package example;

class Class {
int [] cls = {1,2,3,4};
}

public class College{

public static void main(String [] args){
College [] c = new College[3];
c[0] = new College();

College co = new College();
c[1] = co;
co= null;
c[1] = null;
}
}





Questions




  • What are the 5 created objects and 2 that are sent to GC.

  • I don't get it. If we already created 3 objects in the array. then why did we instantiate
    c[0] = new College();

  • I understood that
    College [] c = new College[3]
    is an array of type
    College
    that doesn't hold any object yet. Is that right or wrong?






I'll be sticking to an official java book from now on.

EJP EJP
Answer
int [] cls = {1,2,3,4};

This creates one int[] object.

What are the 5 created objects

Four objects are created [unless they're counting String[] args, which they probably shouldn't].

and 2 that are sent to GC.

Nothing is 'sent to GC' by the code you posted, but when such code is in a method scope everything becomes eligible for GC when it exits, and the references that are nulled make the objects they previously referred to eligible for GC as well, if there are no other references to them.

I don't get it. If we already created 3 objects in the array. then why did we instantiate c[0] = new College();

We didn't 'create 3 objects in the array'. We created an array with three empty slots.

I understood that College [] c = new College[3] is an array of type College that doesn't hold any object yet. Is that right or wrong?

Correct.

Comments