Can you pass the negative number as an Array size in Java?

Java 8Object Oriented ProgrammingProgramming

In general, arrays are the containers that store multiple variables of the same datatype. These are of fixed size and the size is determined at the time of creation. Each element in an array is positioned by a number starting from 0.

You can access the elements of an array using name and position as −

System.out.println(myArray[3]);
//Which is 1457

Creating an array in Java

In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −

int myArray[] = new int[7];

While creating array in this way, you must specify the size of the array.

You can also directly assign values within flower braces separating them with commas (,) as −

int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};

Negative value as the size

No, you cannot use a negative integer as size, the size of an array represents the number of elements in it, –ve number of elements in an array makes no sense.

Still if you do so, the program gets compiled without issues but, while executing it generates a runtime exception of type NegativeArraySizeException

Example

In the following Java program, we are trying to create an array with a negative value as size.

public class Test {
   public static void main(String[] args) {
      int[] intArray = new int[-5];
   }
}

Run time exception

On executing, this program generates a run time exception as shown below.

Exception in thread "main" java.lang.NegativeArraySizeException
at myPackage.Test.main(Test.java:6)
raja
Published on 02-Aug-2019 12:34:01
Advertisements