1.

Which of the below generates a compile-time error? State the reason.

Answer»
  1. INT[] n1 = new int[0];
  2. boolean[] n2 = new boolean[-200];
  3. double[] n3 = new double[2241423798];
  4. char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large. It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number (2241423798) is beyond the CAPACITY of the integer. The maximum array size we can declare is - (2147483647).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The PROGRAM will compile fine. But we get the RUNTIME exception in line 2. The exception is - NegativeArraySizeException

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.



Discussion

No Comment Found