3

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;
}
2
  • where is the issue? Are you asking for how to write a loop or how to add a values in 2-D array? Commented Aug 20, 2014 at 18:12
  • @user3218114 For someone with a relatively high reputation, I'm surprised you haven't changed your default usernames. Commented Aug 20, 2014 at 18:21

2 Answers 2

2

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;
           }
       }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.