Simplest and Best method to print a 2D Array in Java
Given a 2d array arr in Java, the task is to print the contents of this 2d array.
Method 1: Loop method
The first thing that comes to mind is to write a nested for loop, and print each element by arr[i][j].
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
int arr[][]
= { { 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 } };
for ( int i = 0 ; i < arr.length; i++) {
System.out.print( "[" );
for ( int j = 0 ; j < arr[ 0 ].length; j++) {
System.out.print( " " + arr[i][j] + ", " );
}
System.out.print( "], " );
}
}
}
|
Output:
[ 1, 2, 3, ], [ 4, 5, 6, ], [ 7, 8, 9, ],
Method 2: Arrays.deepToString() method (Simplest method)
For this, we will use deepToString() method of Arrays class in the util package of Java. This method helps us to get the String representation of the array. This string can be easily printed with the help of print() or println() method. This is the best and simplest method to print 2D array in Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
int arr[][]
= { { 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 } };
System.out.println(
"Array: "
+ Arrays.deepToString(arr));
}
}
|
Output:
Array: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Last Updated :
25 Nov, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...