Java Program to Interchange Elements of First and Last in a Matrix Across Rows

Last Updated : 21 Aug, 2026

Given a matrix, the task is to swap the first row with the last row while keeping all other rows unchanged.

  • Use a temporary variable to avoid losing values during the swap.
  • The matrix is modified in-place, so no extra matrix is required.

Illustration:

Input: 2 3 4 5
8 9 6 15
13 22 11 18
19 1 2 0

Output: 19 1 2 0
8 9 6 15
13 22 11 18
2 3 4 5

Approach

  • Find the number of rows and columns in the matrix.
  • Traverse each column of the matrix.
  • Swap the elements at the first row (0) and last row (rows - 1).
  • Print the updated matrix.
Java
public class Geeks {

    // Method to swap the first and last rows
    static void swapFirstAndLastRows(int[][] matrix) {

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

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

            int temp = matrix[0][j];
            matrix[0][j] = matrix[rows - 1][j];
            matrix[rows - 1][j] = temp;
        }
    }

    // Method to print the matrix
    static void printMatrix(int[][] matrix) {

        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();
        }
    }

    public static void main(String[] args) {

        int[][] matrix = {
            {2, 3, 4, 5},
            {8, 9, 6, 15},
            {13, 22, 11, 18},
            {19, 1, 2, 0}
        };

        System.out.println("Original Matrix:");
        printMatrix(matrix);

        swapFirstAndLastRows(matrix);

        System.out.println("\nMatrix After Swapping First and Last Rows:");
        printMatrix(matrix);
    }
}

Output
Original Matrix:
2 3 4 5 
8 9 6 15 
13 22 11 18 
19 1 2 0 

Matrix After Swapping First and Last Rows:
19 1 2 0 
8 9 6 15 
13 22 11 18 
2 3 4 5 

Explanation

  • matrix[0][j] represents the element in the first row.
  • matrix[rows - 1][j] represents the element in the last row.
  • A temporary variable is used to swap these elements safely.
  • Only the first and last rows are modified; the middle rows remain unchanged.
  • The method works for both square and rectangular matrices.
Comment