TheAlgorithms/Java · error · IllegalArgumentException

X and Y must be non-null, non-empty, and of the same length.

Error message

X and Y must be non-null, non-empty, and of the same length.

What it means

LinearRegression.fit performs batch gradient descent and requires the x and y arrays to be non-null, non-empty, and equal in length — there must be at least one training sample and every x must map to a y. A null, empty, or mismatched pair makes gradient computation impossible (division by zero on n, or ArrayIndexOutOfBounds).

Source

Thrown at src/main/java/com/thealgorithms/machinelearning/LinearRegression.java:37

     * @param epochs the number of iterations to train the model
     */
    public LinearRegression(double learningRate, int epochs) {
        this.learningRate = learningRate;
        this.epochs = epochs;
        this.m = 0.0;
        this.b = 0.0;
    }

    /**
     * Trains the model on the provided dataset using batch gradient descent.
     *
     * @param x the input feature values
     * @param y the corresponding target values
     * @throws IllegalArgumentException if the arrays are null, empty, or of differing lengths
     */
    public void fit(double[] x, double[] y) {
        if (x == null || y == null || x.length != y.length || x.length == 0) {
            throw new IllegalArgumentException("X and Y must be non-null, non-empty, and of the same length.");
        }

        int n = x.length;

        for (int epoch = 0; epoch < epochs; epoch++) {
            double mGradient = 0;
            double bGradient = 0;

            // Calculate gradients across the entire dataset
            for (int i = 0; i < n; i++) {
                double prediction = (m * x[i]) + b;
                double error = prediction - y[i];

                // Partial derivatives of the Mean Squared Error cost function
                mGradient += error * x[i];
                bGradient += error;
            }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check x != null && y != null && x.length == y.length && x.length > 0 before calling fit.
  2. If the dataset is empty, skip training (return early) rather than calling fit.
  3. When loading paired data, assert equal lengths during load and drop/log mismatched rows.

Example fix

// before
model.fit(x, y); // x.length=0 from empty query

// after
if (x == null || y == null || x.length != y.length || x.length == 0) {
    throw new IllegalArgumentException("invalid training data");
}
model.fit(x, y);
Defensive patterns

Strategy: validation

Validate before calling

if (x == null || y == null || x.length == 0 || x.length != y.length) {
    throw new IllegalArgumentException("x and y must be non-null, non-empty, equal-length");
}
model.fit(x, y);

Prevention

When it happens

Trigger: Calling fit(null, y), fit(x, null), fit(new double[0], new double[0]), or fit(x, y) where x.length != y.length.

Common situations: Empty dataset returned by a filtered query, a CSV parse that produced x and y columns of different lengths (e.g. a malformed row), or null passed when a data source returned no rows.

Related errors


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