Creating and Utilizing Arrays - Review Notes

12 April 2011

An array can be instantiated using the new operator. When you do so, you allocate the required memory space to store your values. Here is an example:

int [] weight = new int[20];

Once you have established the size of the array, it is immutable. All values in an array are of the same type. An array can hold primitives or any object class type.

Every Java array is an iterator so loops can be used whenever there is a need to step through every element stored in an array.

Square brackets used to highlight the index of an array are treated like an operator in Java. They have the highest precedence of all Java operators.

Bounds Checking

Bounds Checking is automatically performed when the index operator is used to insure that the index range falls within the array being referenced. When an array element reference is made, the index must be > or = to 0 and and at least one less than the size of the array. Therefore, when making an index reference of an array that has 17 elements, we would need to refer to an index that falls between 0 and 16. If we do not, an ArrayIndexOutOfBoundsException is thrown. Of course, it is always critical to implement our own bounds checking when we write our programs. Otherwise it is easy to encounter off-by-one-errors in our programs.

One way that we can do our checks is to use the length constant. For example,

for (int index = 0; index < weight.length; index++)

Remember the rule — the maximum index of an array is length-1.

Alternate Array Syntax

The are two ways to declare an array in Java, they are;

int [ ] scores;
int scores [ ];

However, best practices would suggest that we associate the square brackets with the element type. Therefore use

int [ ] scores;

Array Initializers

Array initializers in Java allows us to enter one statement to create and initialize our array. For example;

String[] Dogs = {"Labrador", "Springer", "Brittany", "Golden Retriever"}; 

declares a String array called Dogs and populates our index with Labrador (in index 0), Springer (in index 1), Brittany (in index 2), and Golden Retriever (in index 3). Therefore, the length is 4.

Passing Arrays

Java allows us to pass an entire array to a method as a parameter. When you do, the formal parameter becomes an alias of the original.

R. E. Barksdale

,

---

Commenting is closed for this article.

---