Java Program to Print Boundary Elements of the Matrix

Last Updated : 21 Aug, 2026

The boundary elements of a matrix are the elements present on the outer edges of the matrix. They include the elements of the first row, last row, first column, and last column.

Illustration:

Input :
1 2 3
4 5 6
7 8 9

Output:
1 2 3
4 6
7 8 9

Approach

  • Traverse the matrix using nested loops.
  • Check whether the current element belongs to the first row, last row, first column, or last column.
  • Print the element if it is on the boundary.
  • Print a space for inner elements to preserve the matrix structure.

The boundary condition is:

i == 0 || i == rows - 1 || j == 0 || j == cols - 1

Java
public class Geeks {

    // Method to print boundary elements
    static void printBoundary(int[][] mat) {

        int rows = mat.length;
        int cols = mat[0].length;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {

                // Check whether the element is on the boundary
                if (i == 0 || i == rows - 1 ||
                    j == 0 || j == cols - 1) {

                    System.out.print(mat[i][j] + " ");
                } else {
                    System.out.print("  ");
                }
            }

            System.out.println();
        }
    }

    public static void main(String[] args) {

        int[][] mat = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        printBoundary(mat);
    }
}

Output
1 2 3 
4   6 
7 8 9 

Explanation

  • i == 0 checks the first row.
  • i == rows - 1 checks the last row.
  • j == 0 checks the first column.
  • j == cols - 1 checks the last column.
  • If any condition is true, the element is a boundary element and is printed.
  • Otherwise, a space is printed.
Try It Yourself
redirect icon
Comment