Print a 2 D Array or Matrix in Java
Last Updated :
16 Feb, 2024
Prerequisites: Arrays in Java, Array Declarations in Java (Single and Multidimensional)
Method 1 (Simple Traversal)
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.
Java
import java.io.*;
class GFG {
public static void print2D( int mat[][])
{
for ( int i = 0 ; i < mat.length; i++)
for ( int j = 0 ; j < mat[i].length; j++)
System.out.print(mat[i][j] + " " );
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}
|
Output
1 2 3 4 5 6 7 8 9 10 11 12
Complexity of the above method:
Time Complexity: O(N*M) where N is the number of rows in the matrix and M is the number of columns in the matrix.
Auxiliary Space: O(1)
This is similar to the above. Instead of simple for loops, we use for each loop here.
Java
import java.io.*;
class GFG {
public static void print2D( int mat[][])
{
for ( int [] row : mat)
for ( int x : row)
System.out.print(x + " " );
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}
|
Output
1 2 3 4 5 6 7 8 9 10 11 12
Complexity of the above Method:
Time Complexity: O(N*M) where N is the number of rows in the matrix and M is the number of columns in the matrix.
Auxiliary Space: O(1)
Method 3 (Prints in matrix style Using Arrays.toString())
Arrays.toString(row) converts the complete row is converted as a string and then each row is printed in a separate line.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void print2D( int mat[][])
{
for ( int [] row : mat)
System.out.println(Arrays.toString(row));
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}
|
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)
Method 4 (Prints in matrix style Using Arrays.deepToString())
Arrays.deepToString(int[][]) converts 2D array to string in a single step.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void print2D( int mat[][])
{
System.out.println(Arrays.deepToString(mat));
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}
|
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...