I was reading a book on Java and came across an example in which an array of type double was initialized in a way that I haven't seen before. What type of initialization is it?

double m[][]={
    {0*0,1*0,2*0,3*0},
    {0*1,1*1,2*1,3*1},
    {0*2,1*2,2*2,3*2},
    {0*3,1*3,2*3,3*3}
};
Best Answer


This is array initializer syntax , and it can only be used on the right-hand-side when declaring a variable of array type. Example.

int[] x = {1,2,3,4};
String y = {"a","b","c"};

Use an array constructor instead of the rhs of a declaration of variables

int[] x;
x = new int[]{1,2,3,4};
String y;
y = new String[]{"a","b","c"};

These declarations have the exact same effect a new array is assigned and constructed with specified contents

In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically.

double[][] m = new double[4][4];

for(int i=0; i<4; i++) {
    for(int j=0; j<4; j++) {
        m[i][j] = i*j;
    }
}