-1

I have two-dimensional array

protected MyClass[][] myArray;

in constructor I have this

this.myArray= new MyClass[20][20];

Now, without inicialization (aka this.myArray[2][2] = new MyClass(par0, par1);) the value of this.myArray[2][2] is "null".

Is this guaranteed? And where can I read more about this subject? (for primitive types like int or boolean too)

Thanks

rluks
  • 2,762
  • 8
  • 38
  • 56

3 Answers3

1

Yes, it's guaranteed. Array values are initialized with null (for objects), 0 (for numeric primitives) and false (for boolean primitives), just like fields.

See http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.6-100:

Space is allocated for a new array of that length. If there is insufficient space to allocate the array, evaluation of the array initializer completes abruptly by throwing an OutOfMemoryError. Otherwise, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

(emphasis mine)

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Yes. This behavior is guaranteed. The default value of an Object is null. Therefore the default values for an array of Objects is also null so every element in the array needs to be instantiated. See Default Values in Data Types.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

Yes, it is guaranteed. Every type has a default initialization value:

  • numeric primitives = 0
  • boolean = false
  • all Objects = null
Bohemian
  • 412,405
  • 93
  • 575
  • 722