int [] arr = new int[ 10 ] ;
10 refers to the length, which is the
number of elements in the array.
Construction of arrays specify the length of the array
arr[ 2 ] = 10 ;
2 refers to an index. In this case, the
brackets access a single element from an array. In the example, we
access element 2 (recall that indexing begins at 0, and so even though
it's index 2, it's the third element of the array).
Because arrays are objects, there are methods and instance variables. In particular, arrays have a public instance variable called length, which gives you the length of the array.
Generally, you should avoid using public instance variables to improve encapsulation. However, Java arrays use them, so we must use them as well.
Here's how to print a Java array using the length instance variable.
int [] arr = { 1, 3, 5, 7, 9 } ;
for ( int i = 0 ; i < arr.length ; i++ )
{
System.out.println( "The value at index " + i + " is " + arr[ i ] ) ;
}
In the example above, the length of arr is 5.
The output is:
The output at index 0 is 1 The output at index 1 is 3 The output at index 2 is 5 The output at index 3 is 7 The output at index 4 is 9This is one very convenient feature of Java arrays.
Arrays know their own length.
In C and C++, arrays don't know their own length, so you must often pass an additional variable to keep track of the array's length.