This blog post will show you how to Print a Matrix or 2D Array using a Java program. There are different ways to Print a 2D array, let’s see a few examples for it below:
Example-1. Print Matrix or 2D Array using for loop in Java
package com.javacodepoint.array.multidimensional;
public class Print2DArray {
public static void main(String[] args) {
// Declare and Initialize a 2D array or a Matrix
int arr[][] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
// Print 2D Array using for loops
// Outer for loop for row iteration
for (int i = 0; i < arr.length; i++) {
// Inner for loop for column iteration
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
// To move cursor to new line
System.out.println();
}
}
}
OUTPUT:
1 2
3 4
5 6
Example-2. Print Matrix using for-each loop in Java
package com.javacodepoint.array.multidimensional;
public class Print2DArrayExample2 {
public static void main(String[] args) {
// Declare and Initialize a 2D array or a Matrix
int matrix[][] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
// Print matrix using for-each loop
// Outer for loop for row iteration
for (int[] arr : matrix) {
// Inner for loop for column iteration
for (int i : arr) {
System.out.print(i + " ");
}
// To move cursor to new line
System.out.println();
}
}
}
OUTPUT:
1 2
3 4
5 6
Example-3. Print Matrix using Arrays utils method
In this example, we use deepToString()
utility method of java.util.Arrays
class. The deepToString()
method is used to display the Java multi-dimensional array. In the below example, we are printing a 3×3 size Matrix.
package com.javacodepoint.array.multidimensional;
import java.util.Arrays;
public class Print2DArrayExample3 {
public static void main(String[] args) {
// Declare and Initialize a 2D array (Matrix) of 3x3 size
int matrix[][] = { { 11, 22, 33 }, { 44, 55, 66}, { 77, 88, 99} };
// Print 2D Array or Matrix using deepToString() method of Arrays
System.out.println(Arrays.deepToString(matrix));
}
}
OUTPUT:
[[11, 22, 33], [44, 55, 66], [77, 88, 99]]
See also:
How to Read a Matrix from a User in Java?
Java Program to Copy an Array.
Java Program to Sum of Two Arrays.