Array
- Indexed Collection of fixed homogeneous data elements.
- Readability of code is improved since we represent multiple value by single name.
- In terms of memory point of view it should not be used as once we create an array, there is no chance of increasing or decreasing the size, which gets fixed by using collections.
- Anonymous arrays are for instant use, we cannot specify size at that time else it gives compiler error.
Array Declarations
- Allowed declarations are int[] a (recommended), int a[] and int []a.
- At time of declaration we can't specify the size.
- If we specify dimensions it is possible only for first variable (int[] []a []b] (Not Allowed for b).
Array Construction
- using new operator eg. int[] a = new int[8].
- Its compulsory to specify the size else we get Compiler error.
- 0 is valid size.
- Negative size gives a Runtime Exception (Negative Array Size Exception)
- If we provide any other datatype for size other than int, byte, char or short we get Compiler Error.
- Max allowed size is max value of int.
Array Initialization
- Whenever we create a array every element is initialized with default values, which can be overridden.
- For a object internally toString() is implemented as
- classname@hex_string_of_hashcode
- If any index is accessed which has more than actual size we get ArrayIndexOutOfBoundsException.
Single line Declaration, Construction and Initialization
- int[] a = {10,20,30,40};
- char[] ch = {'a','b','c'};
- String[] s= {"dd","ee","ff"}
- Can be extended for multiple dimension arrays too.
length vs length()
- length is final variable for arrays, it is size. For multidimensional it is base size.
- length() is final variable for string objects it represents no of characters.
Array Element Assignments
- For int type array byte,short,char can be promoted, otherwise we get PLP
- For float type array, long is also included as per above scenario.
- In case of object type we can provide declared type or child object.
- Object > String
- Object > Number > Long, Integer, Double etc
- For Abstract class type, we can provide child objects. (Number > Integer)
- For Interface type, we provide implementation class objects. (Runnable > Thread)
Array Variable Assignments
- Element level promotion are not applicable at array level i.e char[] can't be promoted to int[], except string[] & object[].
- While assigning one array to other, only the reference is assigned. Type should be matched.Underlying elements are not assigned.Non Referenced are eligible for GC.
- Single dimension array cant be assigned to multi and vice versa, else we get compile error (Incompatible types).
0 Comments