Double array initialization in Java

Spread the love

Question Description

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 and where else can it be used?

double m[][]={

Practice As Follows

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

If you’re not on the RHS of a variable declaration, use an array constructor instead:

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 allocated and constructed with the 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;

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.