An array is similar to a table of objects or primitive types, keyed by index. You may have noticed the strange parameter of the default main() method (String args) since the beginning of the book. It is an array. Let's handle this parameter:
$ java ArrayExample This is a test
Argument #1 This
Argument #2 is
Argument #3 a
Argument #4 test
In the code listing 3.15, the array is args. It is an array of String objects (here those objects are the words that have been typed by the user at the program launching). At line 4, One contained object is accessed using its index in the array. You can see that its value is printed on the standard output. Note that the strings have been put in the array with the right order.
At line 1, we instantiate an array of 10 items with non-initialized items. At line 2, we instantiate an array of 10 given items. It will each be given an index according to its order. We can know the size of the array using the length attribute:
Arrays are allocated at runtime, so the specified size in an array creation expression may be a variable (rather than a constant expression as in C). However, the size of an instantiated array never changes. If you need to change the size, you have to create a new instance. Items can be accessed by their index. Beware! The first index is 0:
Note that the length of a two-dimensional array is the number of one-dimensional arrays it contains. In the above example, weirdTwoDimArray.length is 3, whereas weirdTwoDimArray.length is 5.
In the code section 3.58, we defined an array that has three elements, each element contains an array having 5 elements. We could create the array having the 5 elements first and use that one in the initialize block.
i will be the indexes of the main array and j will be the indexes of all the sub-arrays. We have to first iterate on the main array. We have to read the size of the array. Then we iterate on each sub-array. We have to read the size of each array as it may vary. Doing so, we iterate on all the sub-array items using the indexes. All the items will be read in the right order.