NegativeArraySizeException
Published May 26, 2023
Contribute to Docs
NegativeArraySizeException
is a runtime exception in Java that occurs when an application attempts to create an array with a negative size.
Since the NegativeArraySizeException
is an unchecked exception, it does not need to be declared in the throws
clause of a method or constructor.
Example
The NegativeArraySizeException
is thrown in the following example because it assigns a negative size to an array:
public class NegativeArraySizeExceptionExample {public static void main(String[] args) {int[] array = new int[-5];System.out.println("Array length: " + array.length);}}
The output would look like this:
Exception in thread "main" java.lang.NegativeArraySizeException: -5at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:3)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.