Hot Posts

hot/hot-posts

Core Java - Fundamentals II (Arrays)





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

Post a Comment

0 Comments