VOOZH about

URL: https://www.geeksforgeeks.org/java/print-2-d-array-matrix-java/

⇱ Print a 2D Array or Matrix in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print a 2D Array or Matrix in Java

Last Updated : 24 Mar, 2025

In this article, we will learn to Print 2 Dimensional Matrix. 2D-Matrix or Array is a combination of Multiple 1 Dimensional Arrays. In this article we cover different methods to print 2D Array. When we print each element of the 2D array we have to iterate each element so the minimum time complexity is O( N *M ) where N is the number of rows in the matrix and M is the number of columns in the matrix.

Prerequisites: Arrays in Java, Array Declarations in Java (Single and Multidimensional)

Java Program to Print the 2D Array

We can find the number of rows in a matrix mat[][] using mat.length. To find the number of columns in i'th row, we use mat[i].length.

Example 1: Print a 2-dimensional array using nested for-loop.


Output
1 2 3 4 5 6 7 8 9 10 11 12 

Complexity of the above method:

  • Time Complexity: O(N*M).
  • Auxiliary Space: O(1)

Other Methods to Print 2 Dimensional Array

1. Using for-each loop 

Example 2: Printing the 2D Array using the nested for-each loop


Output
1 2 3 4 5 6 7 8 9 10 11 12 

Complexity of the above method:

  • Time Complexity: O(N*M)
  • Auxiliary Space: O(1)

2. Using Arrays.toString() - Prints in matrix style

Example 3: Converts row into a string using Arrays.toString(row) then each row is printed in a separate line. 


Output
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

Complexity of the above method:

  • Time Complexity: O(N*M)
  • Auxiliary Space: O(1)

3. Using Arrays.deepToString()

Example 4: Using Arrays.deepToString(int[][]) converts the 2D array to a string in a single step.


Output
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Complexity of the above method:

  • Time Complexity: O(N*M)
  • Auxiliary Space: O(1)
Comment