Skip to content
Related Articles

Related Articles

Simplest and Best method to print a 2D Array in Java

View Discussion
Improve Article
Save Article
  • Last Updated : 25 Nov, 2019
View Discussion
Improve Article
Save Article

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]]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!