Let's make a simple working array example. You can get the completed code for this example in the downloadable code bundle. It can be found in the Chapter 15/Simple Array Example/MainActivity.java
folder.
Create a project with an Empty Activity and call it Simple Array Example
.
First we declare our array, allocate five spaces, and initialize values to each of the elements. Then we output each of the values to the logcat console. Add the following code to the onCreate
method just after the call to setContentView
:
// Declaring an array int[] ourArray; // Allocate memory for a maximum size of 5 elements ourArray = new int[5]; // Initialize ourArray with values // The values are arbitrary, but they must be int // The indexes are not arbitrary. 0 through 4 or crash! ourArray[0] = 25; ourArray[1] = 50; ourArray[2] = 125; ourArray[3] = 68; ourArray[4] = 47; //Output all the stored values Log.i("info", "Here is ourArray:"); Log.i("info", "[0] = "+ourArray[0]); Log.i("info", "[1] = "+ourArray[1]); Log.i("info", "[2] = "+ourArray[2]); Log.i("info", "[3] = "+ourArray[3]); Log.i("info", "[4] = "+ourArray[4]);
Next, we add each of the elements of the array together, just as we could regular int
type variables. Notice that when we add the array elements together, we are doing so over multiple lines. This is fine as we have omitted a semi-colon until the last operation, so the Java compiler treats the lines as one statement. Add the code we have just discussed to MainActivity.java
:
/* We can do any calculation with an array element provided it is appropriate to the contained type Like this: */ int answer = ourArray[0] + ourArray[1] + ourArray[2] + ourArray[3] + ourArray[4]; Log.i("info", "Answer = "+ answer);
Run the example and see output in the logcat window.
Remember that nothing will happen on the emulator display as all the output will be sent to our logcat console window in Android Studio. Here is the output:
info﹕ Here is ourArray: info﹕ [0] = 25 info﹕ [1] = 50 info﹕ [2] = 125 info﹕ [3] = 68 info﹕ [4] = 47 info﹕ Answer = 315
We declared an array called ourArray
to hold int
variables, and then allocated space for up to 5 of that type.
Next, we assigned a value to each of the five spaces in our array. Remember that the first space is ourArray[0]
and the last space is ourArray[4]
.
Next, we simply printed the value in each array location to the console, and from the output, we can see they hold the value we initialized them to be in the previous step. Then, we added together each of the elements in ourArray
and initialized their value to the answer
variable. We then printed answer
to the console and we can see that indeed, all the values were added together, just as if they were plain old int
types, which they are, but just stored in a different manner.
18.217.144.32