Advertisement
Android SDK

Learn Java for Android Development: Working with Arrays

by

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

Related Posts
  • Code
    PHP
    Object-Oriented Programming in WordPress: Control Structures IIWordpress oop
    WordPress is a powerful CMS that provides a flexible foundation on which to build both sites and applications. If you want to extend WordPress functionality, then you do so via plugins. Although there are a number of different ways to do that, this series has us taking a look at object-oriented programming specifically from the perspective of a beginner and in the context of WordPress. In this post, we're looking at a second set of control structures that allow us to control the flow of code throughout an application.Read More…
  • Code
    WordPress
    Object-Oriented Programming in WordPress: TypesWordpress oop
    In the last post, we took a look at classes which are the building blocks of object-oriented programming. Before we go any further, we need to take a survey of some of the data types that PHP offers. Though we won't be reviewing every type in this particular article, we're going to take a look at some of the more popular types that we'll be using in WordPress development.Read More…
  • Code
    WordPress
    Mastering WordPress Meta Data: Understanding and Using ArraysMetadata
    In the first part of this series, we covered what WordPress meta data is, how it can be retrieved, and the various data types (such as objects or arrays) in which it can be returned. Now it's time to learn about the different types of arrays. When you write an array manually you know what its structure is an what the name of each index is. But when you are building arrays by querying a database, you are going to need to do some detective work to determine the structure of the data returned and the names of the indexes.Read More…
  • Code
    iOS SDK
    Objective-C Succinctly: Blocks0e5ds8 preview image@2x
    Blocks are actually an extension to the C programming language, but they are heavily utilized by Apple's Objective-C frameworks. They are similar to C#'s lambdas in that they let you define a block of statements inline and pass it around to other functions as if it were an object.Read More…
  • Code
    iOS SDK
    Objective-C Succinctly: Data Types0e5ds8 preview image@2x
    Objective-C has two categories of data types. First, remember that Objective-C is a superset of C, so you have access to all of the native C data types like char, int, float, etc. Objective-C also defines a few of its own low-level types, including a Boolean type. Let's call all of these "primitive data types."Read More…
  • Code
    Android SDK
    Android SDK: Java Application ProgrammingAndroid preview@2x
    Our goal in this series is to learn about Android SDK development. So far we explored the development tools, looked at the structure of an Android app project, started to create a user interface, and responded to user interaction. In this tutorial, we will look at the basic structures and concepts in Java that you need to know in order to start developing apps for Android.Read More…