Search code examples
javadynamic-arrays

While Initializing An Object Array what are the defaults values


I have this array Cards[] temp = new Cards[13]; where Cards is a class having 52 object. as per my knowledge this statement will create an array which hold 13 objects of Cards data type. i just want to know before putting the value what values are in this array a garbage of NULL ? i mean after writing

Cards[] temp = new Cards[13];

and before putting real values what are the elements exist after this statement. Either Null or some garbage. more explanation is at compile time the memory of 13 object will dynamically allocate to the array or Cards I want to know what are the values in that memory at compile time. Wither NULL or some garbage ?


Solution

  • In Java all object references are initialized as null if no values provided.

    Cards[] temp = new Cards[13];
    

    After this line temp[0],temp [1] ....temp[12] values are assigned to null.

    You need to create object like below.

    for(int i=0;i<temp.length;i++){
          temp = new Cards();
    }