0

I've a little confusion, when we declare & initialize a 2D array in java like given below

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

This work correct, but when do do the above action like given below

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

Then why it generates an error? Why can't we fix the size of rows and columns and then assign values in same statement? I know that we can do that separately using loops, something like arr[0][0]=345; and so on, but why can't we do it like this?

int arr[4][2]={{1,2,3,4},{4,3,2,1}};
1
  • You can't do it, because that is simply not how Java is designed. Asking why that is, is asking for opinions, which is off-topic. As an aside, although putting array brackets on the variable name is possible in Java, the recommended way is to put them on the type, so int[][] arr instead of int arr[][]. Commented Aug 1, 2021 at 10:33

1 Answer 1

4

That’s because Java is not C language.
When you write int arr[][] = {{1, 2, 3, 4}, {4, 3, 2, 1}};, you declare and initialize a multidimensional array of 2 by 4. It is equivalent to the C language initialization you proposed (int arr[2][4] = {{1, 2, 3, 4}, {4, 3, 2, 1}};)

In Java, we preferably declare arrays in a Java-style manner:

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

where int[][] is just a type identifier, we cannot specify size.
Moreover, in Java, we can initialize a 2D array that is not rectangular:

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

If you want to declare an array of specific size, but don’t want to specify all it’s values at once, the only solution is to use new:

int[][] arr = new int[2][4];
arr[0][0] = 1;
Sign up to request clarification or add additional context in comments.

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.