NegativeArraySizeException in Java — What It Means and How to Fix It

What Java's NegativeArraySizeException means and how to fix it.

Published November 3, 2026

NegativeArraySizeException is thrown when you create an array with a negative size.

What it means and why it happens

Typical causes: computed sizes from user input or arithmetic underflow.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
java.lang.NegativeArraySizeException: -1

Practical examples

Code that triggers it

int[] a = new int[-1];

The fix

int n = computeSize();
if (n < 0) throw new IllegalArgumentException("size < 0");
int[] a = new int[n];

Use collections

List<Integer> list = new ArrayList<>(Math.max(n, 0));

Common mistakes

  • Not validating computed sizes.
  • Integer overflow producing negatives.
  • Using user input directly for sizes.

Key takeaways

  • NegativeArraySizeException: NegativeArraySizeException is thrown when you create an array with a negative size.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Can an array have size 0?

Yes, zero-length arrays are valid.

How do I find which line caused NegativeArraySizeException?

The error message and stack trace show the file and line; start there and work backwards.

More Java articles