Do arrays of objects in Java have default values?
If I build:
Object[][] guy = new Object[5][4];
Do the spots in my array make the default values? Are they empty?
Is there a way to assign default values to each spot in the array?
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.
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
All variables / fields are initialized in Java.
Consult http://docs.oracle.com/javase/specs/
In Java, object initialization defaults to "null".
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
Yes, you can assign a default, for example:
instead:
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'}};