0
0
JavaHow-ToBeginner · 3 min read

How to Print Matrix in Java: Simple Syntax and Example

To print a matrix in Java, use nested for loops to iterate over rows and columns, then print each element. Use System.out.print() for elements and System.out.println() to move to the next row.
📐

Syntax

Use two nested for loops: the outer loop goes through each row, and the inner loop goes through each column in that row. Inside the inner loop, print each element with System.out.print(). After finishing a row, use System.out.println() to move to the next line.

java
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}
💻

Example

This example shows how to print a 3x3 matrix of integers. It demonstrates the nested loops and printing each element with a space, then moving to the next line after each row.

java
public class PrintMatrix {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
1 2 3 4 5 6 7 8 9
⚠️

Common Pitfalls

  • Forgetting to use System.out.println() after each row causes all elements to print on one line.
  • Using System.out.println() inside the inner loop prints each element on its own line, which is usually not desired.
  • Not handling jagged arrays (rows with different lengths) can cause errors if you assume all rows have the same length.
java
/* Wrong way: prints each element on a new line */
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.println(matrix[i][j]); // prints each element on its own line
    }
}

/* Right way: prints elements in rows */
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}
📊

Quick Reference

Remember these tips when printing a matrix in Java:

  • Use nested loops: outer for rows, inner for columns.
  • Use System.out.print() for elements to stay on the same line.
  • Use System.out.println() after each row to move to the next line.
  • Check for jagged arrays to avoid errors.

Key Takeaways

Use nested for loops to iterate over rows and columns of the matrix.
Print elements with System.out.print() and move to next line with System.out.println() after each row.
Avoid printing each element on a new line by not using println inside the inner loop.
Handle jagged arrays carefully by checking each row's length.
Simple nested loops are the most common and clear way to print a matrix in Java.