Arrays are consecutive memory locations of the same data type under one name. Each memory location in a array is referred to as a element. The number of elements is the size or length of the array. The program often calls an element in a array by using the array name followed by the index of the element in brackets which can be any variable or expression that results in a integer, but the index you call must be in the array or it will give you a IndexOutOfBoundsException.
The reason to use arrays is so you can easily access a group of related values, so for example a array would normally hold something like a list of the scores of basketball games during a year, it would be annoying to have to access each score individually, but with a array you can just use a for loop to get to all the scores.
An example of this is:
int sum= 0;
for(int i=0; k<sco.length; k++)
sum+=scores[k];
Instead of doing:
int sum = 0;
sum+= sco1;
sum+=sco2;
. . .
Which also has some problems associated with it because can’t be certain how many scores there are, which means it would be hard to make the method general instead of specific without using a array.
Some things to keep in mind when it comes to arrays are, that if the elements are of a class type then the array contains references to the objects of that type not the object itself, this means that when a array is made its initial values are set to null, while numeric datatypes would have it set to zero and Boolean would have it set to false. Also you cant change a arrays size once it has been declared and initialized, either of the ways shown above. So to make a new one you need to create a entirely new array and copy the values from the old array to the new one. Also, arrays are always passed to methods or constructors as references, so it will be able to change the original array.
**the index starts at zero so the first element in a array will be at index zero NOT one, but when getting the length or size of a array it will start at 1, so length will return the last index +1.**
Array has several different sub-parts, go to the links below to learn about those:
You can make three + dimension arrays but they aren’t used very often and I personally have never had to deal with them, so a post on that won’t happen for a long time.
Other similar topics are :
One thought on “Arrays”
Comments are closed.