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
- Can we change array size in java?
- What is an anonymous array in java?
- Difference between array and arraylist in java?
- What are jagged arrays in java?
- Can array size be negative in java?
- Java program to find duplicate elements in an array.
- Java program to find second largest element in an array of integers.
- Java program to check the equality of two arrays.
- Find all pairs of elements in an integer array whose sum is equal to a given number.
- Java program to find continuous sub array whose sum is equal to a given number
- Java program to find the intersection of two arrays
- Java program to separate zeros from non-zeros in an integer array
- Java program to find all the leaders in an integer array
- Java program to find a missing number in an integer array
- Java program to convert an array to ArrayList and an ArrayList to array
- Java program to count occurrences of each element in an array
- Java program to reverse an array without using an additional array
- Java program to remove duplicate elements from an array
- Java program to find union and intersection of multiple arrays
- Java program to find the most frequent element in an array