Array Basics
When declaring a 1D array in Java, we need a data type, array name and maximum size. Be sure to choose a size large enough, as re-sizing an array in Java is a time and resource consuming exercise. An array of 30 names would be declared as follows:
String [] students = new String[30];
If desired, the declaration (String [] students) and initialization (students=new String[30]) can be separated, as in all variables. Also, the size of the array can be set using a variable. This allows user input or calculations to determine the necessary size of the array.
A 1D array can also be declared, initialized and populated at the same time in Java. This is accomplished by creating a comma separated list of elements, placed in curly braces.
int [] ages = {4, 7, 9};
Traversing 1D Arrays
To traverse a 1D array, we need use a simple for loop. By starting at the value 0, and continuing until one less than the length, we can access all elements in the array.
for(int x=0; x
The code in the loop body can be used for a variety of events such as:
- Outputting the information (System.out.println(students[x])
- Assigning information (students[x] = reader.readLine();)
- Searching for a value (if(students[x].equals("Joe Smith")))
- Keep a running total (sum += studentGrades[x])
That being said, there are some things that we can't do in Java arrays. We cannot add/delete elements within the array without leaving a blank space (null or 0) or writing a method to shift all of the remaining elements. This is one of the downfalls of the array structure.
There is another way to cycle through an array of elements called a for each loop. This loop takes each element and stores it in a variable to be used for that run of the loop. The for each loop does not allow the user to alter the structure of the array (adding/deleteing elements), but does allow access to elements for alteration. A for each loop to output all of the elements of an array would look as follows:
for(String name:students){
System.out.println(name);
}
Parallel Arrays
Sometimes, we have multiple pieces of data that belong together, such as a student name, phone number and grade. Until we learn how to create objects in Java, we can use multiple arrays of the same size to store the information. These arrays are called parallel arrays because the data at each index is partnered with the data in the same index of the other arrays to represent all of the information about a given student. This could present a problem if we sort one of the arrays. We would have to be sure to switch the data in the others or our data would no longer correspond.