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?

+3


source to share


6 answers


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.

+9


source


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

      

+8


source


+1


source


In Java, object initialization defaults to "null".

+1


source


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

+1


source


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'}};

      

0


source







All Articles