secretLion
secretLion

Reputation: 55

How to print a multidimensional array in Java?

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.

Upvotes: 4

Views: 979

Answers (3)

Unmitigated
Unmitigated

Reputation: 89204

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));

Upvotes: 4

Lovesh Dongre
Lovesh Dongre

Reputation: 1344

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);
    }
}

Upvotes: 1

genius42
genius42

Reputation: 243

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.

Upvotes: 1

Related Questions