What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

3 Ways to Print a 2D Array in Java (Print 3x3 Matrix)

  • Feb 09, 2021
  • 5 Minute Read
3 Ways to Print a 2D Array in Java (Print 3x3 Matrix)

An array is one of the most useful data structures in any programming language. Arrays are containers for multiple objects of the same data type, to solve a lot of unique problems that can’t be solved using any other data structure. So, learning how to store data in an array and how to manipulate this data is a very useful skill for any programmer. Arrays need not be one dimensional. Every programming language, including Java, provides for the storage and manipulation of multi-dimensional arrays.

Most practical applications use 2D arrays (also called matrices if their dimensions are similar), so it’s better to focus on learning how to work with 2D arrays.  In this article, we will be having a comprehensive look at 3 different ways for how to print a 2D array in java. We will print out a 3x3 matrix using java.

What is a 2D Array?

As already stated, a 2D array is a representation of elements along two axes: the X-axis and the Y-axis. A 2D array uses two indices to represent the exact location of an element in the memory space. By giving both coordinates to the array definition, one can print the value of the element stored at the given memory location.

As already stated in the previous paragraph, Java (or for that sake, any programming language) does not have a way of representing elements across two memory spaces. It stores elements linearly, but the addressing is done in such a way that one feels that the data is stored along two axes. There are two ways of figuring out the addressing mapping: representing the row first and the column second (row-major) or focusing on the column first and the row second (column-major).

The 2D array is also sometimes also referred to as a Matrix.

Declaration

Java allows only one type of declaration for 2D arrays. The generalized format is:-

[][] = new [][];

One example of the declaration of an int array with 40 rows and 50 columns can be as follows: -

int arr[][] = new int[40][50];

Initialize with values

2D arrays can be initialized with data at the time of declaration, or it can be done after declaration. In general, if an array with static values is used, then its declaration and initialization are considered to have been done together. 2D arrays can be imagined to be a collection of multiple arrays coupled together, or a simple row-wise or column-wise collection of data.

Examples of both types include:

int arr[][] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } };

This initialization is for a 2X3 int array having 2 rows and 3 columns.

int arr[][] = { 1 , 2 ,

                        4 , 5  ,

                        6 , 7 };

This initialization is for a 3X2 int array having 3 rows and 2 columns.

3 Different ways to print 2D Array in Java

If you want to print a 2D array in Java, there are 3 main methods:

1) Array.toString()

One of the best ways to traverse a 2D array in Java, perhaps, is to simply convert the array to string and print it. A 2D array can also be imagined to be a collection of 1D arrays aligned either row-wise or column-wise. Simply traversing along one axis and considering the data to be aligned along the other axis in the form of 1D arrays while making use of a special conversion function called Arrays.toString() for converting these 1D arrays to strings will allow us to print their value easily. This is a more efficient way of printing an array since it involves only one loop as compared to two in most other methods (even if you consider the time complexity of Arrays.toString()).

Note: For using the Arrays.toString() function, the java.util package has to be imported, as it contains all of the functions necessary to work with arrays – including the toString() conversion function.

import java.util.*;

class Array { 
  
    public static void convertToString(int arr[][]) 
    { 

        for (int n = 0 ; n < arr.length ; n++)
        {
            System.out.println(Arrays.toString(arr[n])); 
        } 
            
    } 
  
    public static void main(String args[])
    { 
        int arr[][] = { { 23, 70, 39 }, 
                        { 51, 64, 47 }, 
                        { 81, 11, 105 } }; 
        convertToString(arr); 
    } 
} 

Output:

 [23, 70, 39]

 [51, 64, 47]

 [81, 11, 105]

2) For loop

If you want to try out something a bit less complicated, there’s always a ‘for’ loop for printing all of the values in the array. All you need to do is traverse each row and then traverse each column under each row. Generally, the ‘for’ loop is used because it makes visualization of the transitions easier for the programmer. This method is the most commonly used while working with 2D arrays.

import java.util.*;

class Array { 
  
    public static void convertToString(int arr[][]) 
    { 

        for (int n = 0 ; n < arr.length ; n++)
        {
            System.out.println(Arrays.toString(arr[n])); 
        } 
            
    } 
  
    public static void main(String args[])
    { 
        int arr[][] = { { 23, 70, 39 }, 
                        { 51, 64, 47 }, 
                        { 81, 11, 105 } }; 
        convertToString(arr); 
    } 
} 

Output:

 23, 70, 39

 51, 64, 47

 81, 11, 105

3) ‘While’ Method

The ‘while’ method is more complicated to handle for a beginner. It requires manually handling the updates for the loop variable. Nevertheless, being one of the loops available with the Java programming language, it is necessary to pick it up and work with it. The while loop is very useful in situations where the exact dimensions of the array are not known beforehand, and the ‘for’ loop cannot be used in such situations.

class Array { 
  
    public static void convertToString(int arr[][]) 
    { 
        int n = 0,k = 0;
        while (n != arr.length)
        {
            while (k != arr[n].length)
            {
                System.out.print(arr[n][k] + " ");
                k++;
            }
            k = 0;
            n++;
            System.out.println("");
        }
            
    } 
  
    public static void main(String args[])
    { 
        int arr[][] = { { 23, 70, 39 }, 
                        { 51, 64, 47 }, 
                        { 81, 11, 105 } }; 
        convertToString(arr); 
    } 
}

Output:

 23, 70, 39

 51, 64, 47

 81, 11, 105

Note: In all of the above questions, you will find the usage of something called arr.length. As many of you might have guessed, it is used for finding the length of the array. In 2D arrays, arr.length returns the number of rows it has, and performing the same operation on any one of its indices (for example arr[0].length) will return the number of columns in the array. It’s great that now you know how to print matrix in java, now you should also learn sorting algorithms in java.

Conclusion

Working with 2D arrays is not as complicated as you think. Java’s feature of abstraction prevents the programmer from ever worrying about any underlying memory representation of the data in the array. Learning to traverse through and how to print a 2D array in Java is much needed for programmers. It is one of the most important skills that one needs to pick up while going through the concept of 2D arrays. This article tells you 3 different ways to print matrix in java (3x3 matrix) that should be enough to get you started on your feet.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Arkadyuti Bandyopadhyay
Hi, I am Arkadyuti, a developer and open source enthusiast with quite some experience in content writing. I wish to make the switch to a full-stack developer one day.