# java.lang.NegativeArraySizeException: -1

**Code:** `NegativeArraySizeException` · **Category:** Java · **Seen on:** Java

An array was created with a negative length.

## Meaning

Usually the length comes from a calculation (subtraction, `indexOf` result -1, or an overflowed int) that ended below zero.

## Common causes

- Size computed as `a - b` with b greater
- `indexOf` returning -1 used as a size
- Integer overflow producing a negative number
- Corrupt or unexpected input length field

## Quick fix

1. Validate the size before allocating
2. Check `indexOf` results
3. Use `Math.max(0, n)` or `Math.addExact` to catch overflow

## Detailed fix by platform

### Java

1. `if (n < 0) throw new IllegalArgumentException("size=" + n);`

## How to diagnose

1. **Value** — Printed size?
2. **Source** — Computation or input?
3. **Overflow** — Large ints?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/java/negativearraysizeexception)
