sumanth232
sumanth232

Reputation: 587

2D array static initialisation in java

How to initialise the below 2D static array ? The following works:

static int[][] arr = { {1,2}, {3,4} };
static int[][] arr = new int[][]{ {1,2}, {3,4} };

but what if I want to initialise with a larger data maybe using a for loop ?

class Abc {
    static int[][] arr;
}

Upvotes: 3

Views: 4197

Answers (2)

Eran
Eran

Reputation: 393781

Here's an example of how to initialize the array in a static initializer block. Of course, it's not very interesting, since all the integers in the array are identical.

class Abc {
    static int[][] arr;

    static {
       arr = new int[100][300];
       for (int i=0;i<arr.length;i++) {
           for (int j=0;j<arr[i].length;j++) {
               arr[i][j] = 7;
           }
       }
    }
}

Upvotes: 2

Matthieu
Matthieu

Reputation: 16397

You can add a static initializer block. You can see the documentation here.

Upvotes: 2

Related Questions