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.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]
GO TO FULL VERSION