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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With