Java NegativeArraySizeException

tarunsamanta's avatar
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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

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: -5
at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:3)

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours