Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 231
sumanth232 Avatar asked Jul 13 '26 23:07

sumanth232


1 Answers

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;
           }
       }
    }
}
like image 86
Eran Avatar answered Jul 16 '26 14:07

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!