4
int arr[][] = new int[2][];

I am a beginner in Java and I couldn't understand why this is valid while we initialize a multidimensional array in Java. And I was trying to print a multidimensional array using

System.out.println(Arrays.toString(arr));

and I couldn't see values; instead what it prints was object's address.

1
  • 1
    What is printed is not the memory address, but the hash of the object in hex format, see the Object::toString documentation. As to the initialization: If one initializes a multidimensional array, one only has to define outermost dimension. One should remember that a multidimensional array is just an array of arrays. Thus each inner array can have a different size. Commented Jul 4, 2020 at 16:57

3 Answers 3

4

int arr[][] = new int[2][]; creates an array of two one-dimensional arrays, where each one can have an arbitrary length. Only the first dimension needs to be specified for multidimensional array initializations.

You can use Arrays.deepToString to print the elements of a multidimensional array.

System.out.println(Arrays.deepToString(arr));
Sign up to request clarification or add additional context in comments.

Comments

1

The declaration is valid because int[][] is an array of arrays. So int[x] is an array itself. And if you declare int[2][] you can have up to 2 array inside that array but you don't specify the size of the inner arrays.

That's also the reason why Arrays#toString() is not working. Because you just #toString the inner arrays.

Comments

1

To understand why this works properly

int arr[][] = new int[2][];

We need to know what are Jagged arrays in Java

Jagged array is array of arrays such that member arrays can be of different sizes

int[][] arr = new int[2][];

// row 0 gets 5 columns
arr[0] = new int[5];
// row 1 gets 11 columns
arr[1] = new int[11];

So to create an array we just need to pass the number of rows since number of columns can be variable

How do you traverse a Jagged Array

int a[][] = new int[2][];
a[0] = new int[2];
a[1] = new int[1];

a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;

for(int i[]: a) {
    for(int j: i) {
        System.out.println(j);
    }
}

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.