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].
// Java program to print 2d array // using Loop method import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Get the array
int arr[][]
= { { 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 } };
// Print the array with the help of loop
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
// Java program to print 2d array // using Arrays.deepToString() method import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Get the array
int arr[][]
= { { 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 } };
// Print the array
System.out.println(
"Array: "
+ Arrays.deepToString(arr));
}
} |
Output:
Array: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Article Tags :