What is a Matrix / 2D Array in Java?

“A matrix is a collection of numbers arranged into a fixed number of rows and columns.” Usually these are real numbers. In general, matrices can contain complex numbers but for the sake of simplicity we will only use whole numbers here. Let’s have a look at what a matrix looks like. Here is an example of a matrix with 4 rows and 4 columns.Matrix in Java - 2D Arrays - 2
Fig 1: A simple 4x4 matrix
In order to represent this matrix in Java, we can use a 2 Dimensional Array. A 2D Array takes 2 dimensions, one for the row and one for the column. For example, if you specify an integer array int arr[4][4] then it means the matrix will have 4 rows and 4 columns. Or you can say for each row there will be 4 columns. The total size / number of cells in a matrix will be rows*columns = mxn = 4x4 = 16.Matrix in Java - 2D Arrays - 3
Fig 2: The matrix[4][4] in Fig 1 represented as 2D Array in Java

Declare & Initialize a 2D Array

Here are some different ways to either only declare the size of the array, or initialize it without mentioning the size.
public class Matrices {

	public static void main(String[] args) {

		// declare & initialize 2D arrays for int and string
		int[][] matrix1 = new int[2][2];
		int matrix2[][] = new int[2][3];

           //the size of matrix3 will be 4x4
		int[][] matrix3 = { { 3, 2, 1, 7 },
					   { 9, 11, 5, 4 },
					   { 6, 0, 13, 17 },
					   { 7, 21, 14, 15 } };

		String[][] matrix4 = new String[2][2];

           //the size of matrix5 will be 2x3
           // 3 cols because at max there are 3 columns
		String[][] matrix5 = { { "a", "lion", "meo" },
				            { "jaguar", "hunt" } };
	}
}

2D Array Traversal

We all know how to traverse regular arrays in Java. For 2D arrays it’s not hard either. We commonly use nested ‘for’ loops for this. Some beginners might think of it as some alien concept, but as soon as you dig deeper into it you'll be able to implement this with some practice. Have a look at the following snippet. It only displays the number of columns corresponding to each row for your thorough understanding.
public class MatrixTraversal {
	public static void main(String[] args) {

	    int[][] matrix = new int[4][4];
	    for (int i = 0; i < matrix.length; i++)
	    {
		 // length returns number of rows
		 System.out.print("row " + i + " : ");
		 for (int j = 0; j < matrix[i].length; j++)
		 {
		    // here length returns # of columns corresponding to current row
		    System.out.print("col " + j + "  ");
		 }
	    System.out.println();
	   }
	}
}
Output
row 0 : col 0 col 1 col 2 col 3 row 1 : col 0 col 1 col 2 col 3 row 2 : col 0 col 1 col 2 col 3 row 3 : col 0 col 1 col 2 col 3

How to Print a 2D Array in Java?

After you’re familiar with 2D Array traversal, let’s look at a few ways of printing 2D Arrays in Java.

Using Nested “for” loop

This is the most basic way to print the matrix in Java.
public class MatrixTraversal {

    public static void printMatrix(int matrix[][])
    {
        for (int i = 0; i < matrix.length; i++)
	  {
	    // length returns number of rows
	    for (int j = 0; j < matrix[i].length; j++)
	    {
	      // here length returns number of columns corresponding to current row
		// using tabs for equal spaces, looks better aligned
		// matrix[i][j] will return each element placed at row ‘i',column 'j'
		System.out.print( matrix[i][j]  + "\t");
	     }
	     System.out.println();
	   }
	}

	public static void main(String[] args) {

		int[][] matrix = { { 3, 2, 1, 7 },
					 { 9, 11, 5, 4 },
					 { 6, 0, 13, 17 },
					 { 7, 21, 14, 15 } };
		printMatrix(matrix);
	}
}
Output
3 2 1 7 9 11 5 4 6 0 13 17 7 21 14 15

Using “for-each” loop

Here’s another way to print2D arrays in Java using “foreach loop”. This is a special type of loop provided by Java, where the int[]row will loop through each row in the matrix. Whereas, the variable “element” will contain each element placed at column index through the row.
public class MatrixTraversal {

	public static void printMatrix(int matrix[][]){
		for (int [] row : matrix)
		{
			// traverses through number of rows
			for (int element : row)
			{
				// 'element' has current element of row index
				System.out.print( element  + "\t");
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {

		int[][] matrix = {  { 3, 2, 1, 7 },
					  { 9, 11, 5, 4 },
					  { 6, 0, 13, 17 },
					  { 7, 21, 14, 15 } };
		printMatrix(matrix);
	}
}
Output
3 2 1 7 9 11 5 4 6 0 13 17 7 21 14 15

Using “Arays.toString()” method

Arrays.toString() method in Java, converts every parameter passed to it as a single array and uses its built in method to print it. We’ve created a dummy String 2D array to play around. The same method also works for integer arrays. We encourage you to practice it for your exercise.
import java.util.Arrays;
public class MatrixTraversal {
	public static void printMatrix(String matrix[][]){

		for (String[] row : matrix) {
			// convert each row to a String before printing
			System.out.println(Arrays.toString(row));
		}
	}

	public static void main(String[] args) {

		String [][] matrix = {  { "Hi, I am Karen" },
						{ "I'm new to Java"},
						{ "I love swimming" },
						{ "sometimes I play keyboard"} };
		printMatrix(matrix);
	}
}
Output
[Hi, I am Karen] [I'm new to Java] [I love swimming] [sometimes I play keyboard]

Code Explanation

In the first iteration, String[]row will read “Hi, I am Karen” as an Array, convert it to a String and then print it. That’s how all iterations will take place. The utility provided here is that you don’t have to keep track of any indexes (i, j) or nested loops.

Conclusion

2D Arrays in Java are the most simpler of the multi-dimensional arrays. By the end of this article we hope you’re not afraid of using them, rather ready for rolling up your sleeves for some serious work. You can run all of these sample codes or debug line by line as per your convenience. But in the end, we’d like to advise (like always) that skill comes with great practice & patience. Hope you have fun learning experience with 2D Arrays in Java. Good Luck!Max Heap in Java - 6