Arrays are basically lists of things. This list can contain both objects and primitive data. The basic array can be declared and instantiated as such:
(data type)[ ] (arrayname) = new (data type) [(number of elements)];
Since arrays are considered as objects, the declaration and instantiation follow the pattern of other objects. So, if I wanted the array to store a total of ten names, I would make the array like so:
String[ ] names = new String[10];
Arrays have index values for every element they contain. If I had an array called nums that contained the numbers 1, 2, and 3, the number 1 would have the index position of 0, the number 2 would have index position 1 and the number 3 would have the index position 2 and so on.
Like Strings, arrays have a method that returns the length of the object. In the case of arrays, you would call the method .length. The .length method for arrays does not need the double parentheses.
So, if you wanted to know the length (or number of elements) of the array names, you would do this:
names.length;
We now go on to loops. This is quite simple. Looping through an array is pretty easy and intuitive. If I were to use a for loop to go through every element of the array names which contains 10 String objects, it would look something like this:
for (int i = 0; i < names.length; i++)
{
//body of the loop
}
Leave a Reply