How to check whether a matrix is a square matrix in Java

1 Answer

0 votes
public class SquareMatrixCheck {

    public static boolean isSquareMatrix(int[][] matrix) {
        // Check if the number of rows equals the number of columns
        int rows = matrix.length; // Number of rows
        for (int[] row : matrix) {
            if (row.length != rows) {
                return false; // If any row's length is not equal to the number of rows = not square
            }
        }
        return true; // All rows have the same length as the number of rows
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {5, 8, 9, 10},
            {1, 4, 6, 13},
            {7, 3, 0, 18},
            {6, 8, 9, 20}
        };

        if (isSquareMatrix(matrix)) {
            System.out.println("The matrix is a square matrix.");
        } else {
            System.out.println("The matrix is not a square matrix.");
        }
    }
}



/*
run:

The matrix is a square matrix.

*/

 



answered Oct 7, 2025 by avibootz
...