TheAlgorithms/Java · error · IllegalArgumentException

Matrix must not be null or empty

Error message

Matrix must not be null or empty

What it means

Thrown by StochasticMatrix.validateMatrix when the matrix is null, has zero rows (matrix.length == 0), or its first row has zero length (matrix[0].length == 0). A stochastic (Markov transition) matrix must have rows of probabilities to verify, so an empty/null matrix has nothing to validate. The check only inspects matrix[0], so a non-empty first row passes even if later rows differ.

Source

Thrown at src/main/java/com/thealgorithms/matrix/StochasticMatrix.java:71

        for (int j = 0; j < cols; j++) {
            double sum = 0.0;
            for (int i = 0; i < rows; i++) {
                if (matrix[i][j] < 0) {
                    return false;
                }
                sum += matrix[i][j];
            }
            if (Math.abs(sum - 1.0) > TOLERANCE) {
                return false;
            }
        }
        return true;
    }

    private static void validateMatrix(double[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            throw new IllegalArgumentException("Matrix must not be null or empty");
        }
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Confirm the transition matrix source yields at least one row and one column.
  2. Build the matrix with explicit dimensions before populating probabilities.
  3. Guard the call: skip validation if the model genuinely has no states.

Example fix

// before
double[][] P = loadTransitions(state);
StochasticMatrix.isStochastic(P); // throws if empty

// after
double[][] P = loadTransitions(state);
if (P == null || P.length == 0 || P[0].length == 0) {
    throw new IllegalStateException("No transitions defined for state " + state);
}
StochasticMatrix.isStochastic(P);
Defensive patterns

Strategy: validation

Validate before calling

if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
    throw new IllegalStateException("Transition matrix is empty");
}
StochasticMatrix.isStochastic(matrix);

Type guard

static boolean isUsableTransitionMatrix(double[][] m) {
    return m != null && m.length > 0 && m[0].length > 0;
}

Prevention

When it happens

Trigger: Passing a null transition matrix, a newly-allocated double[0][], or a matrix whose first row is an empty double[0] array. Common when a transition table loaded from input produced no columns.

Common situations: Empty Markov model definition, a parser that produced no transition data, or a default-constructed matrix before probabilities are filled.

Related errors


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