Do arrays of objects in Java have default values?
Yes, fields in new arrays are initialized to zero in Java.
You can use the method Arrays.fill()
to fill all the fields in an array with a specific value.
If you have short length arrays where you statically know what to put them in, you can use array initializers :
Object[][] guy = { { obj1, obj2, null, obj3 }, { ... }, ... };
You have to enter a full array with all fields (20 in your case) for this, so if you want to put the same value in all places it fill()
is probably more convenient.
Arrays of primitive types. initialized with various 0s and false
for boolean arrays (if you don't use an initializer). Array initialization rules are the same as for field initialization and can be found here in the Java Language Specification.
source to share
The existing answers are correct, but there is one bit in your specific example. Although referenced arrays are set to zero by default, multidimensional arrays have an implicit first dimension.
For example, in your case, the first dimension will not be NULL, but will actually point to a different array:
Object[][] guy = new Object[5][4];
System.out.println(guy[0]);
--> Output will be [Ljava.lang.Object;@5e743399
source to share
Primitive types are initialized with default values, reference types are NOT initialized (so they are zero)
Try the code snippet to see what's going on public class ArraysSample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Object[][] objAr = new Object[4][5];
for (Object[] objects : objAr) {
for (Object object : objects) {
System.out.print(object + "\t");
}
System.out.println();
}
int[][] primitievArray = new int[4][5];
for (int[] is : primitievArray) {
for (int i : is) {
System.out.print(i + "\t");
}
System.out.println();
}
}
}
null null null null null null null null null null null null null null null null null null null null null null 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 0
source to share