Core Java

OCA Java 8 Preparation : Arrays

An array in Java is itself an ‘Object’ which is used to store collection of values. You can choose to store a collection of primitives or a collection of objects in an array. When storing primitives, the actual values are stored whereas when storing the objects, array elements hold the references to those objects.

A contiguous space is allocated for an array based on its size .This helps in accessing the elements quickly.

int[] array1 = new int[10];
array1[0] = 1;
array1[1] = 2;
int[] array2 = new int[] {1,2,3};
String[] strArray = new String[] {"Jack", "Joe"};
String strArr[] = {"Jack", "Joe"};
int[][] arrMulti = {{1,2}, {3,4}};

Above are few declarations used to create arrays. Arrays array1 and array2 hold primitive type values, array1 specifies only the size and later fills up the elements in those spaces whereas array2 specifies  its elements directly.

The third array declared above , ‘strArray‘ (size=3), is the one which hold the references to the objects and not the values. This is because String is an object, not a primitive type.

Index for an array always starts at 0. Arrays can be either one or multi-dimensional.

Array Declaration :

In OCA exam you might be tested to identify valid and invalid array declarations as part of some complex code presented to you which might seem requiring some other complex knowledge, for instance, complex looping on arrays. Remember below rules for array declaration :

  1. Size of an array can never be specified during an array declaration.
  2. Square brackets can follow either the variable name or its type.For multidimensional array , it can follow both of them.
int[] arrayOfIntegers; //valid
String arrayOfStr[]; //valid
int[] multiDimArr[]; //valid
int[][] multiDimArr; //valid
int multiDim[][]; //valid
int intArr[5]; //invalid
int[5] multiDimArr[3]; //invalid
String[5] strArray; //invalid

Array Allocation :

As we have already told you that array is an object in Java, so you now understand that new keyword will be used to allocate memory to arrays.However there are some basic rules to remember related to array space allocation for your OCA Exam.

  1. It is must to specify the array size when trying to allocate memory to it.
  2. The size of the array must be evaluated to int value. You can’t create an array with its size specified as a floating-point number.
  3. For a multidimensional(2D) array, it is possible to specify the size only in the first square bracket.
int[] arrayInt;
int[] multiDimArr[];
arrayInt = new int[5]; //valid
arrayInt = new int[2*5]; //valid
arrayInt = new int[2.67]; //invalid
multiDimArr = new int[5][6], //valid
multiDimArr = new int[5][]; //valid
mutliDimArr = new int[][5]; //compilation fails
multiDimArr = new int[7]; //invalid

One important point to understand is that once the array is allocated memory, all the array elements store the default values unless specified. Elements of type primitive types stores 0 for integral types(byte,short, int, long), 0.0 for decimal types(float, double), false for boolean and ‘\u000’ for char data. Elements in an array which store objects default to null. Try printing the values on your favourite IDE to grasp this concept by heart.

For multidimensional array , if you specify  the size only in first square bracket, the values of that 2D array is defaulted to null, considering it to be holding object values. For example, try executing below code .

public class Test{
    public static void main(String ar[]){
        int[] multiDimArr[] = new int[5][];
        System.out.println(multiDimArr[1]); //prints null
    }
}

Array Initialization

Initializing arrays is easiest of all. You just need to access any particular element using its index value.

int[] arr = new int[5];
arr[0] = 1;
System.out.println(arr[0]);

When trying to access an array element using an invalid index( index < 0 or index >= arr.length ), the code compiles fine but a runtime exception – ArrayIndexOutOfBoundException is thrown. Moreover, compiler expects you to pass an int value (or any type that can be auto-typecasted to int) as an index while trying to access its elements. Any attempt to pass long or float without explicit typecasting will fail to compile.

int[] arr = new int[5];
arr[2] = 10;
arr[2.8] = 1; //fails to compile
arr[-7] = 20; //will throw Runtime exception

Combining it all together :

It is also possible to declare, allocate and initialize an array all in one line.However , remember the following rules :

  1. You are not allowed to specify the size of the array as it is computed based on count of the values that are assigned to it.
  2. You can either use curly braces {} or  a new keyword with values passed[referred to as anonymous array].
  3. It’s relevant to understand that if you choose to declare and initialize an array using two separate lines of code, you’ll use a new keyword to initialize the values.
int[] array1 = new int[]{1,2,3}; //valid
int[] array2 = {1,2,3}; //valid
int[][] multiDimArr1 = {{1,2}, {3,4}}; //valid
int[] multiDimArr2[] = new int[][]{ {1,2}, {3,4}}; //valid
int arrayInt[];
arrayInt = new int[] {1,2,3}; //valid

int[] arrayInvalid1 = new int[3]{1,2,3}; //invalid
int arrayInvalid2[];
arrayInvalid2 = {1, 2, 3}; //invalid
int arrayValid[];
arrayValid = new int[]{1,2,3}; //this is valid

Important Members of Array :

  1. Array has a property length, which returns the length of the array. Note : String has a method length() whereas for arrays, length is a property.( i.e arr.length)
  2. clone() : This method helps us to create a clone of an array.

Sorting & Searching Arrays :

The class java.util.Arrays provides methods to perform sort and search operations on an array.

Sorting is done based on the natural ordering of elements in an array. Also, it is must to have all the elements of an array to be mutually comparable or else a ClassCastException is thrown.

String[] arr = {"Zack","Zavier","James"};
java.util.Arrays.sort(arr); //Natural ordering
System.out.println(arr); // [James, Zack, Zavier]

Object[] arrObjects = {"Hello", 2, 3.45};
java.util.Arrays.sort(arrObjects); //throws ClassCastException

Binary search is always performed on a sorted array and Java API helps us to do that with a method binarySearch() in java.util.Arrays class. This method takes an array of almost any type along with a key to look for and returns the index of the key, if it exists.The array passed as an input must be sorted in natural ascending order or the results will be unpredictable.

If the key is not found in the array, this method returns a value corresponding to -(insertionPoint +1) where insertionPoint is the index of the element where the key would have been found if it would have been present in the array.

If there are duplicate elements in an array with same value as the key, then there is no guarantee of which element will be found first.

int[] arr = new int[] {1,2,3,5,6};
int index1 = java.util.Arrays.binarySearch(arr,3);
System.out.println(index1); //print 2
int index2 = java.util.Arrays.binarySearch(arr,4);
System.out.println(index2); //print -4

Asymmetric Arrays :

Since an array is of type object in Java so it is possible to define an asymmetric array. Refer the code below to understand it better.

String[][] ar = { {"Harry", "Jack"}, null, {"Joe","Joseph","Marry"}};

System.out.println(ar[0][1]); //prints Harry
System.out.println(ar[0][2]);//prints Jack
System.out.println(ar[1]);// prints null
System.out.println(ar[1][1]);// throws NullPointerException
/* throws NullPointerException as toString Can't be invoked on null */
System.out.println(ar[1].toString());
System.out.println(ar[2].toString());//prints object representation

 

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *