TheAlgorithms/Java · error · IllegalArgumentException

Matrix is empty

Error message

Matrix is empty

What it means

Thrown by MatrixTranspose.transpose(int[][]) when matrix is null OR matrix.length == 0. Note the Javadoc claims NullPointerException for null and IllegalArgumentException for empty, but the implementation routes both cases to this single IllegalArgumentException ('Matrix is empty'), so null input does NOT produce the documented NPE.

Source

Thrown at src/main/java/com/thealgorithms/matrix/MatrixTranspose.java:33

 * @author Rajat-Jain29
 * @version 11.0.9
 * @since 2014-03-31
 */
public final class MatrixTranspose {
    private MatrixTranspose() {
    }

    /**
     * Calculate the transpose of the given matrix.
     *
     * @param matrix The matrix to be transposed
     * @throws IllegalArgumentException if the matrix is empty
     * @throws NullPointerException     if the matrix is null
     * @return The transposed matrix
     */
    public static int[][] transpose(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            throw new IllegalArgumentException("Matrix is empty");
        }

        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] transposedMatrix = new int[cols][rows];
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                transposedMatrix[i][j] = matrix[j][i];
            }
        }
        return transposedMatrix;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Null-and-size-check before calling and handle the empty case explicitly.
  2. If you rely on the documented NPE-vs-IAE split, note the implementation differs; do not branch on exception type for null.
  3. Use Optional or an empty-matrix sentinel instead of null.

Example fix

// before
int[][] t = MatrixTranspose.transpose(m);

// after
if (m == null || m.length == 0) {
    return new int[0][0];
}
int[][] t = MatrixTranspose.transpose(m);
Defensive patterns

Strategy: validation

Validate before calling

if (matrix == null || matrix.length == 0) {
    return new int[0][0]; // or throw a domain exception
}
int[][] t = MatrixTranspose.transpose(matrix);

Prevention

When it happens

Trigger: Call transpose(null), transpose(new int[0][]), or pass a matrix reference that was never populated. Also reachable if a grouping operation yielded zero rows.

Common situations: Empty result sets materialized as 2D arrays, an uninitialized field, or a parser returning an empty array for a blank input.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/7ac0bbbdf905b777. Report an issue: GitHub.