Important Observations about Array in Java?
The followings are interesting observations about arrays in java. You may be asked in the interviews or Java certification exams about these observations.
1) The size of an array can not be negative. If you give size of an array as negative, you don’t get any errors while compliing. But, you will get NegativeArraySizeException at run time.
2) The size of an array must be an integer or an expression which results an integer. Auto-widening is also allowed.
3) Declaration and instantiating of an array strictly must be of same type. No auto-widening, auto-boxing and auto-unboxing is allowed. But only auto-upcasting is allowed.
4) The type of elements of an array must be compatible with type of the array object. If you try to store non-compatible element in an array object, you will get ArrayStoreException at run time.
5) If you are supplying the contents to the array without new operator, then it should be at the time of declaration only. Not at any other places.
6) While creating multi dimensional arrays, you can not specify an array dimension after an empty dimension
7) You can create an anonymous array i.e an array without reference.
8) While assigning one array reference variable to another, compiler checks only type of the array not the size.
9)The size of an array can not be changed once you define it. You can not insert or delete array elements after creating an array. Only you can change is the value of the elements. This is the main drawback of arrays.
An array is a container that holds data (values) of one single type. For example, you can create an array that can hold 100 values of int type.
In Java, you can initialize arrays during declaration or you can initialize (or change values) later in the program as per your requirement.
You can easily access and alter array elements by using its numeric index
In Java, you can declare an array of arrays known as multidimensional array