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.
Arrays.fill(array, new MyObject()) only creates a single object which is then assigned to all elements, which might be unintended in many use cases with object arrays.The existing answers are all correct, but there is one bit to add in your particular example. Although reference arrays are defaulted to null, multi-dimensional arrays have the first dimension implictly created.
For example, in your case the first dimension wont be null, but will in fact point to another array:
Object[][] guy = new Object[5][4];
System.out.println(guy[0]);
--> Output will be [Ljava.lang.Object;@5e743399
Numbers. And booleans are false.Primitive types are initialized by default values, Referenced types are NOT initialised (so they are null)
Try to run code snippet to see what happens 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
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Yes you can have default assigning, for instance :
instead of:
char[][] c = new char[5][4];
you can:
char[][] c = {{'a','b','c','x','B'}, {'A','Z','w','Z','S'},
{'A','Z','w','Z','S'},{'A','Z','w','Z','S'}};
Char needs to be char here.