An array is one of the most useful data structures in any programming language. So, learning how to store data in an array and how to manipulate this data is a very useful skill. In this article, we will be having a comprehensive look at various ways how to print a 2D array in Java.
What is a 2D Array?
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 a 2D array, also called a matrix if their dimensions are similar.
A 2D array is a data structure that represents a collection of elements in a two-dimensional grid form. A two-dimensional array has rows and columns, that look like a grid.
It 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.
Elements in a 2D Array are accessed using two indices: one for the row and one for the column. The first index represents the row number, and the second index represents the column number. This allows you to locate and manipulate elements in the array based on their row and column positions.
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 they 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.
Example:
int arr[][] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } };
4 Ways to Print 2D Array in Java
If you want to print a 2D array in Java, there are 4 easy methods to learn for programmers:
1) Array.toString()
One of the best ways to print a 2D array in Java is to simply convert the array to a string. A 2D array can also be imagined to be a collection of 1D arrays aligned either row-wise or column-wise. We can use the Arrays.toString() functions for converting these 1D arrays to strings, which 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()).
Here is an example to check:
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]
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.
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.
To print a 2D array using a loop, 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.
Here is an example of using For loop to print a 2D array in Java:
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.
Check the example below:
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 methods, you will find the usage of something called arr.length, which is 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 matrices in Java, now you should also learn sorting algorithms in Java.
4) Using Arrays.deepToString() in Java
Java’s Arrays.deepToString() is a built-in method in java.util.Arrays class. It can be used to convert a multi-dimensional array into a string representation of the array. It can also be done for nested arrays.
The deepToString() method works recursively on the elements of the array to convert each and every element into its string representations. These converted representations of the array are printed as a list of elements, inside square brackets [].
Example:
import java.util.Arrays; public class Example { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(Arrays.deepToString(matrix)); } }
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In the above example, we first created a 2D array named ‘matrix’ and initialized it with three rows and three columns and gave it values. The Arrays.deepToString() method was then called and printed out the result of the ‘matrix’ array as a list of elements.
Conclusion
Working with 2D arrays is not as complicated as you think. Learning to traverse through and print a 2D array in Java is a much-needed skill. This article tells you different ways to Print a Matrix that should be enough to get you started on your feet.