In this article, we will provide an overview of Java Arrays. We will describe how to declare, instantiate and initialize single and multidimensional arrays in Java. We will introduce arrays, which enable you to deal with a number of variables of the same type through a single variable name. This is part of a larger series of articles to help you prepare for the java associate exam. The previous article that you can read is "Tutorial:Review of Java Operators for the Java Certification Exam"

Using Java Arrays

The basic built-in Java data types generally will have an identifier that corresponds to a single variable. In the case of when you want to handle sets of values of the same type such as 1,000 primes, you want to avoid having to name them individually. Instead you want to use an array.

An array is an object that is a named set of variables of the same type. Each variable in the array is called an array element. To reference a particular element in an array, you use the array name combined with an integer value of type int, called an index. You put the index between square brackets following the array name; for example, data[99] refers to the element in the data array corresponding to the index value 99. The index for an array element is the offset of that particular element from the beginning of the array. The first element has an index of 0, the second has an index of 1, the third an index of 2, and so on. Thus, data[99] refers to the hundredth element in the data array. The index value does not need to be an integer literal. It can be any expression that results in a value of type int that is equal to or greater than zero. For loops are very useful for processing array elements.

Java Array Variables

An array variable and the array it refers to are separate entities. The memory that is allocated for an array variable stores a reference to an array object, not the array itself. The array object itself is a distinct entity that is elsewhere in memory. All variables that refer to objects store references that record the memory locations of the objects they refer to. You are not obliged to create an array when you declare an array variable. You can first create the array variable and later use it to store a reference to a particular array. You could then declare the integer array variable primes with the following statement:

Java Code: Declare an integer array variable
int[] primes;
An alternative notation for declaring an array variable is the following:

Java Code: Declare an integer array variable
int primes[];
Here the square brackets appear after the variable name, rather than after the type name. This is exactly equivalent to the previous statement so you can use either notation. Many programmers prefer the original notation, as int[] tends to indicate more clearly that the type is an array of values of type int.

Defining a Java Array

Once you have declared a Java array variable, you can define an array that it references:

Java Code: Define an array of 10 integers
primes = new int[10];
This statement creates an array that stores 10 values of type int and stores a reference to the array in the variable primes. The reference is simply where the array is in memory. You could also declare the array variable and define the array of type int to hold 10 prime numbers with a single statement, as shown in the figure below:

Tutorial:Review of Java Arrays for the Java Certification Exam-d4-arrayofintegers.jpg
Figure: An Array of integers

The first part of the definition specifies the type of the array. The element type name, int in this case, is followed by an empty pair of square brackets to indicate you are declaring an array rather than a single variable of type int. The part of the statement that follows the equal sign defines the array. The keyword new indicates that you are allocating new memory for the array, and int[10] specifies you want capacity for 10 variables of type int in the array. Because each element in the primes array is a variable of type int that requires 4 bytes, the whole array occupies 40 bytes, plus 4 bytes for the primes variable to store the reference to the array. When an array is created like this, all the array elements are initialized to a default value automatically. The initial value is zero in the case of an array of numerical values, is false for boolean arrays, is ‘\u0000’ for arrays storing type char, and is null for an array of objects of a class type. The listing below shows example of an array of declaration:

Java Code:
double[] myArray = new double[100];
We have a declaration of the array variable myArray. The statement also defines the array because the array size is specified. The variable myArray refers to an array of 100 values of type double, and each element has the value 0.0 assigned by default. Because there are 100 elements in this array, the legal index values range from 0 to 99.

The Length of a Java Array

You can refer to the length of the Java array—the number of elements it contains—using length, a data member of the array object. For example, for the array myArray that you defined in the previous listing, you can refer to its length as myArray.length, which has the value 100. You can use the length member of an array to control a numerical for loop that iterates over the elements of an array.

Accessing Array Elements

You refer to an element of an array by using the array name followed by the element's index value enclosed between square brackets. You can specify an index value by any expression that produces a zero or positive result of type int. If you use a value of type long as an index, you get an error message from the compiler; if your calculation of an index uses long variables and the result is of type long, you need to cast it to type int.

You refer to the first element of the primes array as primes[0], and you reference the fifth element in the array as primes[4]. The maximum index value for an array is one less than the number of elements in the array. Java checks that the index values you use are valid. If you use an index value that is less than 0, or greater than the index value for the last element in the array, an exception is thrown known as an ArrayIndexOutOfBoundsException.

Reusing Array Variables

An array variable is separate from the array that it references. Rather like the way an ordinary variable can store different values at different times, you can use an array variable to store a reference to different arrays at different points in your program. If you have declared and defined the variable primes in the following manner:

Java Code: Allocate an array of 10 integer elements
int[] primes = new int[10];
This produces an array of 10 elements of type int. If later, you want to use the array variable primes to refer to a larger array, with 50 elements, for example, you can simply write the following:

Java Code: Allocate an array of 50 integer elements
primes = new int[50];
Now the primes variable refers to a new array of values of type int that is entirely separate from the original. When this statement is executed, the previous array of 10 elements is discarded, along with all the data values you may have stored in it. The variable primes can now be used to reference only elements of the new array. This is shown in the figure below:

Tutorial:Review of Java Arrays for the Java Certification Exam-d4-reassigningarrayvariable.jpg
Figure: Re-Assigning an Array Variable

After executing the statement shown in the figure, the array variable primes now points to a new integer array of 50 elements with index values running from 0 to 49. Although you can change the array that an array variable references, you can't alter the type of value that an element stores. All the arrays referenced by a given variable must correspond to the original type that you specified when you declared the array variable. The variable primes, for example, can only reference arrays of type int[]. You have used an array of elements of type int in the illustration, but the same thing applies equally well when you are working with arrays of elements of type long or double or of any other type. Of course, you are not restricted to working with arrays of elements of primitive types. You can create arrays of elements to store references to any type of object, including objects of the classes that you define yourself.

Initializing Arrays

You can initialize the elements in an array with your own values when you declare it, and at the same time determine how many elements it has. To do this, you simply add an equal sign followed by the list of element values enclosed between braces following the specification of the array variable. The listing below show how you can define and initialize an array:

Java Code: An array of 7 elements
int[] primes = {2, 3, 5, 7, 11, 13, 17};
This creates the primes array with sufficient elements to store all of the initializing values that appear between the braces—seven in this case. The array size is determined by the number of initial values so no other information is necessary to define the array. The values are assigned to the array elements in sequence, so in this example primes[0] has the initial value 2, primes[1] has the initial value 3, primes[2] has the initial value 5, and so on through the rest of the elements in the array.

If you want to set only some of the array elements to specific values explicitly, you can create the array with the number of elements you want and then use an assignment statement for each element for which you supply a value. The listing below shows how the assignment statement works with Java arrays:

Java Code: Assignment Statement of Arrays
int[] primes = new int[100]; 
primes[0] = 2; 
primes[1] = 3;
The first statement declares and defines an integer array of 100 elements, all of which are initialized to zero by default. The two assignment statements then set values for the first two array elements. You can also initialize the elements in an array using a for loop to iterate over all the elements and set the value for each:

Java Code: Set Array Value
double[] data = new double[50];	// An array of 50 values of type double 
for(int i = 0 ; i < data.length ; ++i) { 
   // i from 0 to data.length-1
   data[i] = 1.0;
}
For a Java array with length elements, the index values for the elements run from 0 to length-1. The for loop control statement is written so that the loop variable i starts at 0 and is incremented by 1 on each iteration up to data.length-1. When i is incremented to data.length, the loop ends. Thus, this loop sets each element of the array to 1. Using a for loop in this way is one standard idiom for iterating over the elements in an array. You see later that you can use the collection-based for loop for iterating over and accessing the values of the array elements. Here you are setting the values so the collection-based for loop cannot be applied.

Using a Utility Method to Initialize a Java Array

You can also use a method that is defined in the Arrays class in the java.util package to initialize an array. For example, to initialize the data array defined as in the previous fragment, you could use the following statement:

Java Code: Fill all elements of data with 1.0
Arrays.fill(data, 1.0);
The first argument to the fill() method is the name of the array to be filled. The second argument is the value to be used to set the elements. This method works for arrays of any primitive type. Of course, for this statement to compile correctly you need an import statement at the beginning of the source file:

Java Code: Import Statement
import java.util.Arrays;
This statement imports the Arrays class name into the source file so you can use it as you have in the preceding code line. Without the import statement, you can still access the Arrays class using the fully qualified name. In this case the statement to initialize the array is:

Java Code: Fill all elements of data with 1.0
java.util.Arrays.fill(data, 1.0);
This is just as good as the previous version of the statement because fill() is a static method in the Arrays class, you could import the method name into your source file:
import static java.util.Arrays.fill;

Now you can call the method with the name unadorned with the class name:

Java Code: Fill all elements of data with 1.0
fill(data, 1.0);
You can also set part of an array to a particular value with another version of the fill() method:

Java Code: fill() method
double[] data = new double[100];
fill(data, 5, 11, 1.5);
This specifies that a range of elements in the array are to be set to a given value. You supply four arguments to this version of the fill() method. The first argument is the name of the array, data. The second argument is the index of the first element to be set. The third argument is 1 beyond the index of the last element to be set. The fourth argument is the value for the elements. This sets all the elements from data[5] to data[10] inclusive to 1.5.

There are versions of the fill() method for each of the primitive element types so you can use it to set values for any array of elements of a primitive type.

Initializing a Java Array Variable

You can initialize an array variable with a reference to an existing array of the same type. For example, you could declare the following array variables:

Java Code: Array Variable Declaration
long[] even = {2L, 4L, 6L, 8L, 10L}; long[] value = even;
Here the array reference stored in even is used to initialize the array value in its declaration. The figure below demonstrates the effect on the array:

Click image for larger version. 

Name:	D4-ArrayOfIntegers.jpg 
Views:	7 
Size:	21.2 KB 
ID:	3753
Figure: Array Initialization in Declaration

You have created two array variables, but you have only one array. Both arrays refer to the same set of elements, and you can access the elements of the array through either variable name—for example, even[2] refers to the same variable as value[2]. One use for this is when you want to switch the arrays referenced by two variables. If you were sorting an array by repeatedly transferring elements from one array to another, by flipping the array you were copying from with the array you were copying to, you could use the same code. For example, if you declared array variables as

Java Code: Array Variable Declaration
double[] inputArray = new double[100];    // Array to be sorted
double[] outputArray = new double[100];   // Reordered array
double[] temp;                            // Temporary array reference
when you want to switch the array referenced by outputArray to be the new input array, you could write the following:

Java Code: Array References
temp = inputArray;        		// Save reference to inputArray in temp
inputArray = outputArray;     	// Set inputArray to refer to outputArray
outputArray = temp;			// Set outputArray to refer to what was inputArray
None of the array elements are moved here. Just the addresses of where the arrays are located in memory are swapped, so this is a very fast process. Of course, if you want to replicate an array, you have to create a new array of the same size and type, and then copy the value of each element of the old array to your new array.

Using Arrays

You can use array elements in expressions in exactly the same way as you might use a single variable of the same data type. For example, if you declare an array samples, you can fill it with random values between 0.0 and 100.0 with the following code:

Java Code: Assigning Values to Array
double[] samples = new double[50];	// An array of 50 double values for(int i = 0; i < samples.length; ++i) {
samples[i] = 100.0*Math.random();	// Generate random values
}
This shows how the numerical for loop is ideal when you want to iterate through the elements in an array to set their values. Of course, this is not an accident. A major reason for the existence of the for loop is precisely for iterating over the elements in an array.
To show that array elements can be used in exactly the same way as ordinary variables, I could write the following statement:

Java Code: Array Declarations
double result = (samples[10]*samples[0] – Math.sqrt(samples[49]))/samples[29];
This is a totally arbitrary calculation, of course. More sensibly, to compute the average of the values stored in the samples array, you could write

Java Code: Computing Average using an Array
double average = 0.0;	// Variable to hold the average
for(int i = 0; i < samples.length; ++i) { 
   average += samples[i];	// Sum all the elements
} 
average /= samples.length;	// Divide by the total number of elements
Within the loop, you accumulate the sum of all the elements of the array samples in the variable average. You then divide this sum by the number of elements. Notice how you use the length of the array, samples.length, all over the place. It appears in the for loop and in floating-point form as a divisor to calculate the average. When you use arrays, you often find that references to the length of the array are strewn all through your code. As long as you use the length member of the array, the code is independent of the number of array elements. If you change the number of elements in the array, the code automatically deals with that. You should always use the length member when you need to refer to the length of an array never use explicit values.

Using the Collection-Based for Loop with an Array

You can use a collection-based for loop as an alternative to the numerical for loop when you want to process the values of all the elements in an array. It is possible to rewrite the code fragment from the previous listing that calculated the average of the values of the samples array. The listing for this is shown below:

Java Code: Array Samples
double average = 0.0; 		// Variable to hold the average
for(double value : samples) {
   average += value; 		// Sum all the elements
}
average /= samples.length;	 // Divide by the total number of elements
The for loop iterates through the values of all elements of type double in the samples array in sequence. The value variable is assigned the value of each element of the samples array in turn. Thus, the loop achieves the same result as the numerical for loop that you used earlier—the sum of all the elements is accumulated in average. When you are processing all the elements in an array, you should use the collection-based for loop because it is easier to read and less error-prone than the numerical for loop. Of course, when you want to process only data from part of the array, you still must use the numerical for loop with the loop counter ranging over the indexes for the elements you want to access.

It's important to remember that the collection-based for loop iterates over the values stored in an array. It does not provide access to the elements for the purpose of setting their values. Therefore, you use it only when you are accessing all the values stored in an array to use them in some way. If you want to recalculate the values in the array, use the numerical for loop.

Arrays of Arrays

You have worked only with one-dimensional arrays up to now, that is, arrays that use a single index. Why would you ever need the complications of using more indexes to access the elements of an array?

Consider a specific example. Suppose that you have a fanatical interest in the weather, and you are intent on recording the temperature each day at 10 separate geographical locations throughout the year. After you have sorted out the logistics of actually collecting this information, you can use an array of 10 elements corresponding to the number of locations, where each of these elements is an array of 365 elements to store the temperature values. You declare this array with the following statement:

Java Code: 2D Array Declaration
float[][] temperature = new float[10][365];
This is called a two-dimensional array because it has two dimensions — one with index values running from 0 to 9, and the other with index values from 0 to 364. The first index relates to a geographical location, and the second index corresponds to the day of the year. That's much handier than a one-dimensional array with 3650 elements, isn't it?
The figure below shows the organization of the two-dimensional array.

Tutorial:Review of Java Arrays for the Java Certification Exam-d4-twodimensionalarray.jpg
Figure: Two-Dimensional Array

There are 10 one-dimensional arrays that make up the two-dimensional array, and they each have 365 elements. In referring to an element, the first pair of square brackets encloses the index for a particular array and the second pair of square brackets encloses the index value for an element within that array. So to refer to the temperature for day 100 for the sixth location, you use temperature[5][99]. Because each float variable occupies 4 bytes, the total space required to store the elements in this two-dimensional array is 10x365x4 bytes, which is a total of 14,600 bytes.

For a fixed value for the second index in a two-dimensional array, varying the first index value is often referred to as accessing a column of the array. Similarly, fixing the first index value and varying the second, you access a row of the array. The reason for this terminology should be apparent from the figure above:

You could equally well have used two statements to create the last array, one to declare the array variable and the other to define the array:

Java Code: Defining the Array
float [][] temperature;	// Declare the array variable 
temperature = new float[10][365];	// Create the array
The first statement declares the array variable temperature for two-dimensional arrays of type float. The second statement creates the array with ten elements, each of which is an array of 365 elements of type float.

Arrays of Arrays of Varying Length

When you create an array of arrays, the arrays in the array do not need to be all the same length. You could declare an array variable, samples, with the following statement:

Java Code: Variable Length Arrays
float[][] samples;	// Declare an array of arrays
This declares the array object samples to be of type float[][]. You can then define the number of elements in the first dimension with the statement:

Java Code: Define 6 elements, each being an array
samples = new float[6][];
The samples variable now references an array with six elements, each of which can hold a reference to a one-dimensional array. You can define these arrays individually if you want. This is shown in the listing below:

Java Code: Defining Arrays Individually
samples[2] = new float[6];	// The 3rd array has 6 elements 
samples[5] = new float[101];	// The 6th array has 101 elements
This defines two of the six possible one-dimensional arrays that can be referenced through elements of the samples array. The third element in the samples array now references an array of 6 elements of type float, and the sixth element of the samples array references an array of 101 elements of type float. Obviously, you cannot use an array until it has been defined, but you could conceivably use these two and define the others later—not a likely approach, though!

If you want the array samples to have a triangular shape, with one element in the first row, two elements in the second row, three in the third row, and so on, you can define the arrays in a loop as shown in the listing below:

Java Code: Define Array via a Loop
for(int i = 0; i < samples.length; ++i) { 
   samples[i] = new float[i+1];	// Allocate each array
}
The effect of this is to produce the array layout that is shown in the figure below:

Tutorial:Review of Java Arrays for the Java Certification Exam-d4-multidimensionalarray.jpg
Figure: Multidimensional Array

The 6 elements in the array occupy 24 bytes. When you need a two-dimensional array with rows of varying length, allocating them to fit the requirement can save a considerable amount of memory compared to just using rectangular arrays where the row lengths are all the same.

To check out that the array is as shown in the figure above, you can define it in a program using the code fragments you have just seen and include statements to display the length member for each of the one- dimensional arrays.

You could use a numerical for loop to initialize the elements in the samples array, even though the rows may differ in length:

Java Code: Array Initialization
for(int i = 0; i < samples.length; ++i) { 
   for(int j = 0 ; j < samples[i].length ; ++j) {
      samples[i][j] = 99.0f;	// Initialize each element to 99 
   }
}
Of course, for the loops to execute properly the arrays must already have been created. The upper limit for the control variable in the inner loop is samples[i].length. The expression samples[i] references the current row in the two-dimensional array so samples[i].length is the number of elements in the current row. The outer loop iterates over the rows in the samples array, and the inner loop iterates over all the elements in a row.

You can also achieve the same result with slightly less code using the fill() method from the Arrays class that you saw earlier:

Java Code: fill() method=for(int i = 0; i &lt; samples.length; ++i) { <br /> java.util.Arrays.fill(samples[i
, 99.0f); // Initialize elements in a row to 99
}
Because the fill() method fills all the elements in a row, you need only one loop that iterates over the rows of the array.

Multidimensional Arrays

You are not limited to two-dimensional arrays either. You can develop arrays of even three dimensions or more. Fore example, If you collect lego blocks, you could arrange to store the results of your lego counting in the array declared and defined in the following statement:

Java Code: Three-Dimensional Array Declaration
long[][][] lego = new long[10][10][30];
The array of lego blocks, has three dimensions. It provides for holding lego blocks for each of up to 30 legos in length, with 10 legos in width and 5 legos deep.

You can envisage this as just a three-dimensional array, but remember that legos is really an array of five elements deep, each of which holds a reference to a two-dimensional array, and each of these two-dimensional arrays can be different. For example, if you really want, you can declare the array legos with the statement:

Java Code: Three two-dimensional arrays
long[][][] legos = new long[3][][];
Each of the three elements in the first dimension of legos can hold a different two-dimensional array, so you could specify the first dimension of each explicitly with the following statements:

Java Code: Defining Multidimensional Array
legos[0] = new long[4][]; 
legos[1] = new long[2][]; 
legos[2] = new long[5][];
These three arrays have elements that each hold a one-dimensional array, and you can also specify the sizes of these independently. Note how the empty square brackets indicate there is still a dimension undefined. You could give the arrays in each of these elements random dimensions between 1 and 7 with the following code:

Java Code: Multidimensional Array Filling
for(int i = 0; i < legos.length; ++i) // Vary over 1st dimension 
   for(int j = 0; j < legos[i].length; ++j)	// Vary over 2nd dimension
      legos[i][j] = new long[(int)(1.0 + 6.0*Math.random())];
If you can find a sensible reason for doing so, or if you are just a glutton for punishment, you can extend this to four or more dimensions.

Arrays of Characters

All the arrays you have defined have contained elements storing numerical values so far. You can also have arrays of characters. For example, you can declare an array variable of type char[] to hold 50 characters with the following statement:

Java Code: Definition of Array of Characters
char[] message = new char[50];
Keep in mind that characters are stored as Unicode UTF-16 in Java so each element occupies 2 bytes. If you want to initialize every element of this array to a space character, you can either use a for loop to iterate over the elements of the array, or just use the fill() method in the Arrays class, like this:

Java Code: Store a space in every element
java.util.Arrays.fill(message, ‘ ‘);
Of course, you can use the fill() method to initialize the elements with any character you want. If you put ‘\n’ as the second argument to the fill() method, the array elements all contain a newline character.

You can also define the size of an array of type char[] by the characters it holds initially:

Java Code: Defining Character Array
char[] vowels = { ‘a’, ‘e’, ‘i’, ‘o’, ‘u’};
This defines an array of five elements, initialized with the characters appearing between the braces. This is fine for things such as vowels, but what about proper messages?
Using an array of type char[], you can write statements such as:

Java Code: Array of type char
char[] sign = {‘F’, ‘l’, ‘u’, ‘e’, ‘n’, ‘t’, ‘ ‘, ‘G’, ‘i’, ‘b’, ‘b’, ‘e’, ‘r’, ‘i’, ‘s’, ‘h’, ‘ ‘,
‘s’, ‘p’, ‘o’, ‘k’, ‘e’, ‘n’, ‘ ‘, ‘h’, ‘e’, ‘r’, ‘e’};
Well, you get the message—just—but it's not a very friendly way to deal with it. It looks like a collection of characters, which is what it is. What you really need is something a bit more integrated—something that looks like a message but still gives you the ability to get at the individual characters if you want. What you need is a String.

Summary

You should now be thoroughly familiar with how to create and use arrays. Most people have little trouble dealing with one-dimensional arrays, but arrays of arrays are a bit trickier so try to practice using these.