Advertisement

Learn Java for Android Development: Working with Arrays

This quick lesson shows you how to work with arrays in Java. This lesson is part of an ongoing series of tutorials for developers learning Java in order to develop Android applications.

What is an Array?

An array is a common data structure used to store an ordered list of items. The array elements are typed. For example, you could create an array of characters to represent the vowels in the alphabet:

char aVowels[] = {'a','e','i','o','u'};

Much like C or C++, Java arrays are indexed numerically on a 0-based system. This means the first element in the array (that is, ‘a’) is at index 0, the second (‘e’) is at index 1, and so on.

Java makes working with arrays easier than many other programming languages. The array itself is an object (of type array), with all the benefits thereof. For example, you can always check the size of an array using its length property:

int length = aVowels.length;

What Can I Store In An Array?

You can store any object or primitive type in an array. For example, you can store integers in an array:

int aNums[] = { 2, 4, 6 };

Or, you could store non-primitive types like Strings (or any other class) in an array:

String aStooges[] = {"Larry", "Moe", "Curly"};

Sometimes, you may want to store objects of different types in an array. You can always take advantage of inheritance and use a parent class for the array type. For example, the Object class is the mother of all classes… so you could store different types in a single array like this:

float one = 1.0f;
Integer two = new Integer(2);
String three = "three";
Object aObjects[] = {one, two, three};

The elements of a Java object array are references (or handles) to objects, not actual instances of objects. An element value is null until it is assigned a valid instance of an object (that is, the array is initialized automatically but you are responsible for assigning its values).

Declaring Arrays

There are a number of ways to declare an array in Java. As you’ve seen, you can declare an array and immediately provide its elements using the C-style squiggly bracket syntax. For example, the following Java code declares an array of integers of length 3 and initializes the array all in one line:

int aNums[] = { 2, 4, 6 };

You can also declare an array of a specific size and then assign the value of each element individually, like this:

double aPowersOfTwo[] = new double[5];
aPowersOfTwo[0]=Math.pow(2,0);
aPowersOfTwo[1]=Math.pow(2,1);
aPowersOfTwo[2]=Math.pow(2,2);
aPowersOfTwo[3]=Math.pow(2,3);
aPowersOfTwo[4]=Math.pow(2,4);

This is equivalent to creating an array like this:

double aPowersOfTwoExplicit[] = {1.0d, 2.0d, 4.0d, 8.0d, 16.0d};

There are several other ways to create arrays. For example, you can create the array variable and assign it separately using the new keyword. You can also put the array brackets before the variable name, if you desire (this is a style issue). For example, the following Java code defines an array of String elements and then assigns them individually:

String [] aStopLightColors;
aStopLightColors = new String[3];
aStopLightColors[0] = new String("red");
aStopLightColors[1] = new String("yellow");
aStopLightColors[2] = new String("green");

Modifying Array Content

As you have seen, you can assign array values by using the bracket syntax:

You can retrieve array values by index as well. For example, you could access the second element in the array called aStopLightColors (defined in the previous section) as follows:

String strCurrentLightColor = aStopLightColors[1];

Iterating Arrays

Finally, arrays are often used as an ordered list of objects. Therefore, you may find that you want to iterate through the array in order, accessing each element methodically.

There are a number of ways to do this in Java. Because you can always check the size of an array programmatically, you can use any of the typical for or while loop methods you may find familiar. For example, the following Java code declares a simple integer array of three numbers and uses a simple for-loop to iterate through the items:

int aNums[] = { 2, 4, 6 };

for (int i = 0; i < aNums.length; i++) {
    String strToPrint = "aNums[" + i + "]=" + aNums[i]; 
}

Java also provides a very handy for-each loop to iterate through arrays in a friendly fashion. The for-each loop helps avoid silly programming mistakes so common in loops (off-by-one errors, etc.). To use the for-each loop syntax, you need to define your loop variable, then put a colon, and then specify the name of your array. For example, the following code provides the similar loop structure as the previous for-loop shown above:

for (int num : aNums) {
    String strToPrint = num; 
}

As you can see, the for-each loop is slick. However, you no longer know the index while iterating. Thus, it can't be used in all situations.

Conclusion

In this quick lesson you have learned about arrays in Java. Arrays are a fundamental data structure used for Java programming that store an ordered number of objects of a given type in an organized fashion. In Java, arrays are objects themselves and store references to objects, making assignment and use easier (but subtly different) than how arrays are employed in other programming languages.

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Advertisement