can array size be negative in java?

No, array size cannot be negative. If we specify array size as negative, there will be no compile time error. But there will be run time NegativeArraySizeException.

Example

class Main {
   public static void main(String[] args) {
 
      int[] testArray = new int[4];
 
      for (int i = 0; i < testArray.length; ++i) {
         System.out.println(testArray[i]);
      }
   }
}

Output

0
0
0
0

We will get run time error (NegativeArraySizeException), if we specify negative array size. Example

class Main {
   public static void main(String[] args) {
 
      int[] testArray = new int[-4];
 
      for (int i = 0; i < testArray.length; ++i) {
         System.out.println(testArray[i]);
      }
   }
}

Output

Exception in thread "main" java.lang.NegativeArraySizeException 
        at Main.main(Main.java:4)

Interview Questions on Arrays

Please follow and like us:
Content Protection by DMCA.com