Syed Fahad
Syed Fahad

Reputation: 157

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 ?

Upvotes: 0

Views: 925

Answers (4)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26084

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();
}

Upvotes: 2

victorantunes
victorantunes

Reputation: 1169

Please refer to the official docs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Section 'Default Values':

byte    0

short   0

int     0

long    0L

float   0.0f

double  0.0d

char    '\u0000'

String (or any object)      null

boolean     false

That means that each object in your array will have a default value of null. No garbage values like other languages, just null.

You can try it for yourself:

for (int i = 0; i < temp.length; i++) {
    System.out.println(temp[i]);
}

Upvotes: 0

shikjohari
shikjohari

Reputation: 2288

When you said

Cards[] temp = new Cards[13];

it means that you have created and array named temp which contain 13 references. These references can point to 13 Cards object. Also if you have 52 instance variables for the individual cards it will all set to null as they are instance variables. I hope I understood your question well.

Upvotes: 1

Kayaman
Kayaman

Reputation: 73578

They're initialized to null. They can't be garbage.

Also the array holds 13 references, not 13 objects. The last part of your question I didn't understand.

Upvotes: 5

Related Questions