|
An array provides a convenient storage mechanism for data. You can store the elements in ordered fashion . Then you can access any element directly by specifying its position in the array. This position of element within an array is called as the array index.
You can refer to a particular array element using the index mechanism. The array index starts at 0. For example, in an array of 10 elements, the first element has the index of 0 and the tenth element has the index of 9. Consider the following code which creates a names array of 10 Strings:
String[] names = new String[10];
The array will have 10 elements. The individual elements are referred by an index in the square brackets, say for instance, names[5]. All the ten elements from names[0] to names[9] will have a default value null. The element names[10] does not exist and hence it is undefined.
If an array element is referred with a negative index or with index greater than or equal to the size of the array, Java throws an exception called java.lang.ArrayIndexOutOfBoundsException.
Despite its weird declaration syntax, an array object is much like any other Java object. It is inherited from java.lang.Object class. Therefore, it understands all the methods of Object class. Besides the java.lang.Object methods, it also has its own accessible member variable, length. The following code shows how you can find out the size of an array with the length variable.
String[] names = new String[5];
names[0] ="Mickey";
names[1] ="Pluto";
System.out.println(names.length); // Prints 5 on the console
Length gives the size of a constructed array. The names array of String references has five elements. Initially at the time of array construction, each element is initialized to a null reference. Later two actual string references are added and the elements names[2], names[3] and names[4] are still null.