Print Two Dimensional Array in Java

In this post, we will see how to print two dimensional array in Java.


 

In the previous post, we have discussed how to declare and initialize two dimensional arrays in Java. In this post, we will see how to print them.

 

1. Arrays.toString()

We know that a two dimensional array in Java is a single-dimensional array having another single-dimensional array as its elements. We can use Arrays.toString() function to print string representation of each single-dimensional array in the given two dimensional array.

Download   Run Code

Output:

[1, 2, 3]
[4, 5, 6, 7]
null
[8, 9]

 
Above code uses simple for-loop to print the array. We can also use for-each loop to effectively print the array as shown below:

 

2. Inner for loop

Naive solution would to use two loops – outer loop for first dimension and inner loop for second dimension of the two dimensional array.

Download   Run Code

Output:

1 2 3
4 5 6 7

8 9

 
Here’s how we can use for-each loop to effectively print the array:

Since an array is an object in Java, it can be null. The null check in above code is placed to avoid NullPointerException in case any array is null.

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz