Download Java Arrays: Storing and Manipulating Data in Memory and more Study notes Computer Science in PDF only on Docsity! CS121/IS232 Arrays of integers Files and databases store information on a disk, not in memory (RAM). Disk access is much slower than memory access, so when we have a lot of data, it makes more sense to store it in RAM while we are working on it. There are a number of ways to store information in memory. We will start with arrays. An array is an indexed list that in Java begins at zero. 7 9 4 8 12 6 5 19 1 2 0 1 2 3 4 5 6 7 8 9 These numbers might represent the ages of 10 animals. In a program this array might be declared by private int [] animalAges = new int [10]; This says that animalAges is the name of an array of 10 integers. We have to get a new instance of the array in order to allocate space in memory for it. Elements in an array are referred to by their indices. For an array of 10 elements, the indices run from 0 to 9. To access a single element in the array, we use its index: animalAges [4] = 12; or animalAges [4] ++; // Sets the value in the location to 13. The number in the square brackets is the location (index). The value (contents) stored in the array is denoted by animalAges [4]. The entire array is denoted by animalAges. We use a counter to go through the array. If we know how many elements are in the array, we can use a for loop. int sum = 0; for (int count = 0; count < 10; count ++) { sum = sum + animalAges [count]; } Arrays can be used in programs to store any data type. If the datatype is one of the simple types, elements can be assigned directly to a location. We will look at these first. Arrays of simple data can be initialized when they are declared. To create the array above, we could use int [] animalAges = {7, 9, 4, 8, 12, 6, 5, 19, 1, 2}; This is only useful when you know in advance what your data will be. We can change the AnimalManager class and have it read the age data from the file into an array called animalAges. Once the data is in the array, we can use a for loop to add up the ages in the array and then compute the average age. The example below has the changes. As you can see, it is not all that different from the version that computed the sum while reading in the data. That method is more efficient, but we will see other examples later where using an array is necessary. package zoo; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner;