An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables , such as number0 , number1 , ..., and number99 , you declare one array variable such as numbers and use numbers[0] , numbers[1] , and ..., numbers[99] to represent individual variables. This section introduces how to declare array variables, create arrays, and process arrays using indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
dataType[] arrayRefVar;
or
dataType arrayRefVar[]; // This style is allowed, but not preferred
The following code snippets are examples of this syntax:
double [] myList;
or
double myList[]; // This style is allowed, but not preferred
Note
The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. |
Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. Only a storage location for the reference to an array is created. If a variable does not reference to an array, the value of the variable is null . You cannot assign elements to an array unless it has already been created. After an array variable is declared, you can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
This statement does two things: (1) it creates an array using new dataType[arraySize] ; (2) it assigns the reference of the newly created array to the variable arrayRefVar .
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
or
dataType arrayRefVar[] = new dataType[arraySize];
Here is an example of such a statement:
double [] myList = new double [ 10 ];
This statement declares an array variable, myList , creates an array of ten elements of double type, and assigns its reference to myList . Figure 6.1 illustrates an array with sample element values.
Note
An array variable that appears to hold an array actually contains a reference to that array. Strictly speaking, an array variable and an array are different, but most of the time the distinction between them can be ignored. Thus it is all right to say, for simplicity, that myList is an array, instead of stating , at greater length, that myList is a variable that contains a reference to an array of ten double elements. When the distinction makes a subtle difference, the longer phrase should be used. |
When space for an array is allocated, the array size must be given, to specify the number of elements that can be stored in it. The size of an array cannot be changed after the array is created. Size can be obtained using arrayRefVar.length . For example, myList.length is 10.
When an array is created, its elements are assigned the default value of for the numeric primitive data types, '\u0000' for char types, and false for boolean types.
The array elements are accessed through the index. Array indices are -based ; that is, they start from to arrayRefVar.length-1 . In the example in Figure 6.1, myList holds ten double values and the indices are from to 9 .
Each element in the array is represented using the following syntax, known as an indexed variable :
arrayRefVar[index];
For example, myList[9] represents the last element in the array myList .
Caution
Some languages use parentheses to reference an array element, as in myList(9) . But Java uses brackets, as in myList[9] . |
After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the values in myList[0] and myList[1] to myList[2] :
myList[ 2 ] = myList[ ] + myList[ 1 ];
The following loop assigns to myList[0] , 1 to myList[1] , and 9 to myList[9] :
for ( int i = ; i < myList.length; i++) { myList[i] = i; }
Java has a shorthand notation, known as the array initializer , which combines declaring an array, creating an array, and initializing in one statement using the following syntax:
dataType[] arrayRefVar = {value0, value1, ..., value k };
For example,
double [] myList = { 1.9 , 2.9 , 3.4 , 3.5 };
This statement declares, creates, and initializes the array myList with four elements, which is equivalent to the statements shown below:
double [] myList = new double [ 4 ]; myList[ ] = 1.9 ; myList[ 1 ] = 2.9 ; myList[ 2 ] = 3.4 ; myList[ 3 ] = 3.5 ;
Caution
The new operator is not used in the array initializer syntax. Using an array initializer, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. Thus the next statement is wrong: double [] myList; myList = { 1.9 , 2.9 , 3.4 , 3.5 }; |
When processing array elements, you will often use a for loop. Here are the reasons why:
All of the elements in an array are of the same type. They are evenly processed in the same fashion by repeatedly using a loop.
Since the size of the array is known, it is natural to use a for loop.
Here are some examples of processing arrays:
( Initializing arrays with random values ) The following loop initializes the array myList with random values between 0.0 and 99.0 :
for ( int i = ; i < myList.length; i++) { myList[i] = Math.random() * 100 ; }
( Printing arrays ) To print an array, you have to print each element in the array using a loop like the one shown below.
f or ( int i = ; i < myList.length; i++) { System.out.print(myList[i] + " " ); }
Tip
For an array of the char[] type, it can be printed using one print statement. For example, the following code displays Dallas : char [] city = { 'D' , 'a' , 'l' , 'l' , 'a' , 's' }; System.out.println(city); |
( Summing all elements ) Use a variable named total to store the sum. Initially total is . Add each element in the array to total , using a loop like this:
double total = ; for ( int i = ; i < myList.length; i++) { total += myList[i]; }
( Finding the largest element ) Use a variable named max to store the largest element. Initially max is myList[0] . To find the largest element in the array myList , compare each element in myList with max , and update max if the element is greater than max .
double max = myList[ ]; for ( int i = 1 ; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; }
( Finding the smallest index of the largest element ) Often you need to locate the largest element in an array. If an array has more than one largest element, find the smallest index of such an element. Suppose the array myList is { 1 , 5 , 3 , 4 , 5 , 5 }. The largest element is 5 , and the smallest index for 5 is 1 . Use a variable named max to store the largest element and a variable named indexOfMax to denote the index of the largest element. Initially max is myList[0] , and indexOfMax is . Compare each element in myList with max , and update max and indexOfMax if the element is greater than max .
double max = myList[ ]; int indexOfMax = ; for ( int i = 1 ; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } }
What is the consequence if (myList[i] > max) is replaced by (myList[i] >= max) ?
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop , which enables you to traverse the complete array sequentially without using an index variable . For example, the following code displays all the elements in the array myList :
for ( double element: myList) { System.out.println(element); }
You can read the code as "for each element in myList do the following." Note that the variable, element , must be declared the same type as the elements in myList .
In general, the syntax for a foreach loop is
for (elementType element: arrayRefVar) { // Process the element }
You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.
This section presents a program that reads six integers, finds the largest of them, and counts its occurrences. Suppose that you entered 3 , 5 , 2 , 5 , 5 , 5 , as shown in Figure 6.2; the program finds that the largest is 5 and that the occurrence count for 5 is 4 .
An intuitive solution is to first read the numbers and store them in an array, then find the largest number in the array, and finally count the occurrences of the largest number in the array. The program is given in Listing 6.1.
1 import javax.swing.JOptionPane; 2 3 public class TestArray { 4 /** Main method */ 5 public static void main(String[] args) { 6 final int TOTAL NUMBERS = 6; 7 int [] numbers = new int [TOTAL NUMBERS]; 8 9 // Read all numbers 10 for ( int i = 0; i < numbers.length ; i++) { 11 String numString = JOptionPane.showInputDialog( 12 "Enter a number:" ); 13 14 // Convert string into integer 15 numbers[i] = Integer.parseInt(numString); 16 } 17 18 // Find the largest 19 int max = numbers[0]; 20 for ( int i = 1; i < numbers.length ; i++) { 21 if ( max < numbers[i] ) 22 max = numbers[i]; 23 } 24 25 // Find the occurrence of the largest number 26 int count = 0; 27 for ( int i = 0; i < numbers.length ; i++) { 28 if ( numbers[i] == max ) count++; 29 } 30 31 // Prepare the result 32 String output = "The array is " ; 33 for ( int i = 0; i < numbers.length ; i++) { 34 output += numbers[i] + " " ; 35 } 36 37 output += "\nThe largest number is " + max; 38 output += "\nThe occurrence count of the largest number " 39 + "is " + count; 40 41 // Display the result 42 JOptionPane.showMessageDialog( null , output); 43 } 44 } |
The program declares and creates an array of six integers (line 7). It finds the largest number in the array (lines 19 “23), counts its occurrences (lines 26 “29), and displays the result (lines 32 “42). To display the array, you need to display each element in the array using a loop.
Without using the numbers array, you would have to declare a variable for each number entered, because all the numbers are compared to the largest number to count its occurrences after it is found.
Caution
Accessing an array out of bounds is a common programming error that throws a runtime ArrayIndexOutOfBoundsException . To avoid it, make sure that you do not use an index beyond arrayRefVar.length - 1 . Programmers often mistakenly reference the first element in an array with index 1, so that the index of the tenth element becomes 10. This is called the off-by-one error . |
Tip
If you use an IDE such as JBuilder, NetBeans, or Eclipse, please refer to Learning Java Effectively with JBuilder/NetBeans/Eclipse in the supplements. It will show you how to use a debugger to inspect arrays. |
This example writes a program that reads student scores, gets the best score, and then assigns grades based on the following scheme:
Grade is A if score is > = - 10;
Grade is B if score is > = - 20;
Grade is C if score is > = - 30;
Grade is D if score is > = - 40;
Grade is F otherwise .
The program prompts the user to enter the total number of students, then prompts the user to enter all of the scores, and concludes by displaying the grades.
The program reads the scores, then finds the best score, and finally assigns grades to the students based on the preceding scheme. Listing 6.2 gives the solution to the problem. The output of a sample run of the program is shown in Figure 6.3.
1 import javax.swing.JOptionPane; 2 3 public class AssignGrade { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Get number of students 7 String numberOfStudentsString = JOptionPane.showInputDialog( 8 "Please enter number of students:" ); 9 10 // Convert string into integer 11 int numberOfStudents = Integer.parseInt(numberOfStudentsString); 12 13 int [] scores = new int [numberOfStudents]; // Array scores 14 int best = ; // The best score 15 char grade; // The grade 16 17 // Read scores and find the best score 18 for ( int i = ; i < scores.length ; i++) { 19 String scoreString = JOptionPane.showInputDialog( 20 "Please enter a score:" ); 21 22 // Convert string into integer 23 scores[i] = Integer.parseInt(scoreString); 24 if (scores[i] > best) 25 best = scores[i]; 26 } 27 28 // Declare and initialize output string 29 String output = "" ; 30 31 // Assign and display grades 32 for ( int i = ; i < scores.length ; i++) { 33 if (scores[i] >= best - 10 ) 34 grade = 'A' ; 35 else if (scores[i] >= best - 20 ) 36 grade = 'B' ; 37 else if (scores[i] >= best - 30 ) 38 grade = 'C' ; 39 else if (scores[i] >= best - 40 ) 40 grade = 'D' ; 41 else 42 grade = 'F' ; 43 44 output += "Student " + i + " score is " + 45 scores[i] + " and grade is " + grade + "\n" ; 46 } 47 48 // Display the result 49 JOptionPane.showMessageDialog( null , output); 50 } 51 } |
The program declares and creates scores as an array of int type in order to store the students' scores (line 13) after the user enters the number of students into numberOfStudents in lines 7 “11. The size of the array is set at runtime; it cannot be changed once the array is created.
The array is not needed to find the best score, but it is needed to keep all of the scores so that grades can be assigned later on, and it is needed when scores are printed along with the students' grades.