Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do object arrays in Java have default values?

Tags:

java

arrays

If I construct:

Object[][] guy = new Object[5][4];

do the spots in my array have default values? Are they null?

Is there a way to assign default values for every spot in the array?

like image 757
Billy Thompson Avatar asked Feb 17 '13 11:02

Billy Thompson


1 Answers

Yes, fields in new arrays are initialized with null in Java.

You can use the method Arrays.fill() to fill all fields in an array with a specific value.

If you have arrays of short length where you statically know what to put it, you can use array initializers:

Object[][] guy = { { obj1, obj2, null, obj3 }, { ... }, ... };

You have to type out the full array with all fields (20 in your case) for that, so if you want to put the same value in every place, fill() is probably more convenient.

Arrays of primitive types btw. are initialized with the various variants of 0 and with false for boolean arrays (as long as you don't use an initializer). The rules for array initialization are the same as for the initialization of fields, and can be found here in the Java Language Specification.

like image 127
Philipp Wendler Avatar answered Oct 05 '22 23:10

Philipp Wendler