How to print contents of 2D array properly without loop — Java

--

Photo by Michiel Leunens on Unsplash

How to print 2D Array in Java?

While developing code in java, we always wanted to see the output using System.out.println() . This method can not print array or 2D array properly.

But, when it comes to printing the 2D array, the output will be like ` [[I@6ff3c5b5. So, It becomes difficult to identify the changes, which you are actually looking for.

So, In Java we have Arrays.deepToString() method which will properly print nested array.

Let’s see an example below.

package com.arrays;

import java.util.Arrays;

public class SortArray {

public static void main(String[] args) {
// TODO Auto-generated method stub

int[][] arr = {{2, 5, 15},{1, 2, 8},{3, 5, 10},{4,4,20}};
Arrays.sort(arr,(x,y)->{
if(x[1]==y[1])
return x[2]-y[2];
return x[1]-y[1];
});
// Output - [[1, 2, 8], [4, 4, 20], [3, 5, 10], [2, 5, 15]]
System.out.println(Arrays.deepToString(arr));
// Output - [[I@6ff3c5b5
System.out.println(arr);
}
}

The above issue occurs not only with 2D array but also with normal array.

In that case use method Arrays.toString(1Darray)

Let’s see an example

package com.arrays;

import java.util.Arrays;

public class Print1DArray {

public static void main(String[] args) {
// TODO Auto-generated method stub

int[] arr = {34,12,11,89,42,67};

// Output - [34, 12, 11, 89, 42, 67]
System.out.println(Arrays.toString(arr));

// Output - [I@4dc63996
System.out.println(arr);
}
}

If you like my content. Don’t forget to hit the upvote button. 🙏

--

--