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.
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 :
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
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.
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 } }
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
It is also possible to declare, allocate and initialize an array all in one line.However , remember the following rules :
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
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
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