Table of Contents
- Introduction
- What is a 2-dimensional array or matrix in java?
- How to print a 2D array in java?
- Simple Traversal using for and while loop
- Using For-Each Loop to print 2D Array in Java
- Arrays.toString() method to print 2D Array in Java
- Arrays.deepToString() method to print 2D Array in Java
- Using Stream API in Java 8 to print a 2D array
Introduction
In this article, we get a look on How to print a 2D or Two Dimensional array in java.
Arrays are one of the most useful data structures when it comes to data storage. Arrays provide random access to the elements via their index basing which makes both accessing and storing the most efficient.
Hence, it is trivial to know the different ways one can use to print these arrays. So, we will look at different ways to print a 2D array in java with working examples to get a deeper look at Two-dimensional arrays in java.
What is a 2-dimensional array or matrix in java?
A 2D Array or Two-dimensional array, simply put is a representation of elements along the two axes i.e. X axis and the Y axis respectively, typically in the form of a Matrix having elements across the columns of each row. Unlike a 1D array which uses only a single index to store and access elements, A 2D array or a 2D matrix uses two indices to represent an array in memory.
We access elements in a 2D array like this:Â arr[row][column]
A typical 2D array representation has 3 rows and 3 columns:
In the 2D array arr, the first square bracket contains the row index value and the second bracket contains the column index value similar to a matrix. In Java, arrays are allocated memory dynamically with the new keyword and we need to specify the size of the rows and columns at the time of declaration of the array. We declare the 2D array like this:
1 2 3 |
int arr[][] = new int[10][10]; |
Here, 10 is the total number of rows and columns in the matrix respectively. We can also have a matrix or 2D array with varying sizes of rows and columns.
How to print a 2D array in java?
Here we outline 5 possible methods to Print a 2D array in Java
:
- Simple Traversal using for and while loop.
- Using For-each loop
- Using the toString() method of Arrays Class
- Using deepToString() method of Arrays Class.
- Using Streams in Java 8.
Let us have a look at each of these methods in detail.
Simple Traversal using for and while loop
Using this method, we first traverse through each row i
of the 2D matrix then we print the value at each column j
like arr[i][j]
. Hence, we require two Nested For loops to traverse the 2D array. This is a commonly used method to print the 2D array.
Important Points to note:
- In Java, we can use the length field to get the length of the array. So, for a 2D array arr, we can use
arr.length
to get the total number of rows. - Now, since each row of the 2D array is an array itself, so we can use
arr[i].length
to get the length of each row i.e. the total number of columns in the 2D Array, i is the row index of the array. - This assumption will help us in traversing through the 2D array when the row size and column size are not known or when the rows and columns are different in length i.e. Total number of rows ≠Total number of Columns
Let us look at the code implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class Java2Blog { static void print2DArray(int arr[][]) { System.out.println("The 2D Array is : "); System.out.println(); // Loop through all rows for (int i = 0; i < arr.length; i++) // we use arr.length to get rows { // Loop through all elements of current row with arr[i].length to get size of each row array for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); // Add a line break after printing each row } } public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
We can also use the while loop to print the same 2D array but with a different set of counter variables. Let us have a look at the code for this method as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class Java2Blog { static void print2DArray(int arr[][]) { int n = 0,k = 0; System.out.println("The 2D Array using while loop : "); System.out.println(); 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[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
Using For-Each Loop to print 2D Array in Java
In Java, For- Each loop is another interesting technique to traverse arrays, introduced from Java 5. In this loop, instead of declaring a loop counter variable, we declare a reference variable of the same type as the array. It is also known as the Advanced For loop.
Important Points to note:
- When traversing through a 2D array, we declare the reference variable of the type array. Example: int[] row, row is a reference to an int array, and refers to each row of the array.
- For the next nested loop, we can simply go through each element of the reference array row and print the elements.
Let us look at the implementation in code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class Java2Blog { static void print2DArray(int arr[][]) { System.out.println("The 2D Array is : "); System.out.println(); // for each loop for (int[] row : arr) // row refers to each row or array in 2D array arr { // Loop through all elements of the row for (int element : row) { System.out.print(element + " "); } System.out.println(); // Add a line break after printing each row } } public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
Arrays.toString() method to print 2D Array in Java
We can use the toString() method of the Object class to give the String representation of any object. Similarly, the Arrays of java.util package class in java has its own toString() method that represents the array as a String within square brackets. This is permissible as arrays are primarily objects in java, also we employ this method to mainly debug the code to get spontaneous values in the array.
We first loop through each row within the 2D array then we print each array using the Arrays.toString() method.
Let us look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.Arrays; public class Java2Blog { static void print2DArray(int arr[][]) { System.out.println("The 2D Array using toString() is : "); System.out.println(); // for each loop for (int[] row : arr) // row refers to each row or array in 2D array arr { // Print each row using toString System.out.print(Arrays.toString(row)); System.out.println(); // Add a line break after printing each row } } public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
Arrays.deepToString() method to print 2D Array in Java
In the Arrays class, the deepToString() method is an interesting implementation of toString() that returns a String representation of the deep contents of the specified array. It returns all the rows of the 2D array within square brackets.
The syntax of the method is :
1 2 3 |
public static String deepToString(Object[] a) |
This method accepts only arrays as input parameters. Let us look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Arrays; public class Java2Blog { static void print2DArray(int arr[][]) { System.out.println("The 2D Array using deepToString() is : "); System.out.println(); System.err.println(Arrays.deepToString(arr)); } public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
If we want to exclude the square brackets while printing the 2D array using deepToString()
method we can also try replacing them with blank spaces to order and format the output.
Let us look at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Arrays; public class Java2Blog { static void print2DArray(int arr[][]) { System.out.println("The 2D Array replacing the square brackets is : "); System.out.println(); // we replace ',' with blank space and add extra space while printing each row. System.err.println(Arrays.deepToString(arr).replace("],","\n").replace(","," ").replaceAll("[\\[\\]]", " ")); } public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
Using Stream API in Java 8 to print a 2D array
From the advent of Java 8, the introduction of the Stream API and Lambda expressions helped in minimizing the code and add more features of functional programming.
Hence, we can use the stream() method of the Arrays class and add for-each loop implementation with Lamda expressions to print a 2D array. We first take each row as a stream then convert each element in the row as a stream and print the elements in a 2D array.
Note: JDK 8.0 or higher must be installed in your machine to use this method.
Let us look at the code implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Arrays; public class Java2Blog { static void print2DArray(int arr[][]) { System.out.println("The 2D Array using Streams : "); System.out.println(); // we use for each with stream to convert rows of array into a stream. Arrays.stream(arr).forEach((i) -> { Arrays.stream(i).forEach((j) -> System.out.print(j + " ")); System.out.println(); }); } public static void main(String args[]) { int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, // we declare a 2D array with 3 rows & 3 columns. { 7, 8, 9 } }; print2DArray(arr); } } |
Output:
That’s all for the article, we looked at different methods to print a 2D array in java with working examples. You can try the code in your local compiler.
Feel free to reach out for any suggestions/doubts.