Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Using Arrays

You use arrays in a program as you would use any variable, except for the element number in between the square brackets next to the array's name. Once you refer to the element number, you can use an array element anywhere a variable could be used. The following statements all use arrays that have already been defined in this hour's examples:

elfSeniority[193] += 1;
niceChild[94287612] = "Max";
if (hostileAirTravelNations[currentNation] == true)

An important thing to note about arrays is that the first element of an array is numbered 0 instead of 1. This means that the highest number is one less than you might expect. For example, consider the following statement:

String[] topGifts = new String[10];

This statement creates an array of string variables that are numbered from 0 to 9. If you referred to topGifts[10] somewhere else in the program, you would get an error message like the following when you run the program:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
    at Gift.main(Gift.java:4);

Like all of the error messages encountered in Java, this one's a bit hard to decipher. The key thing to note is the part that mentions an exception, because exceptions are another word for errors in Java programs. This exception is an "array out of bounds" error, which means that a program tried to use an array element that doesn't exist within its defined boundaries.

If you want to check the upper limit of an array during a program so you can avoid going beyond that limit, you can use a variable called length that is associated with each array that is created. The length variable is an integer that contains the number of elements an array can hold. The following example creates an array and then reports its length:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
  "Comet", "Cupid", "Donder", "Blitzen", "Rudolph" };
System.out.println("There are " + reindeerNames.length + " reindeer.");

In this example, the value of reindeerNames.length is 9, which means that the highest element number you can specify is 8.

There are two primary ways to work with text in Java: a string or an array of characters. When you're working with strings, one useful technique is to put each character in a string into its own element of a character array. To do this, call the string's toCharArray() method, which produces a char array with the same number of elements as the length of the string.

This hour's first project is an application that uses both of the techniques introduced in this section. The NoSpaces program displays a string with all space characters (' ') replaced with periods ('.').

Enter the text of Listing 9.1 in your word processor and save the file as NoSpaces.java.

Listing 9.1 The Full Text of NoSpaces.java

 1: class NoSpaces {
 2:   public static void main(String[] arguments) {
 3:     String mostFamous = "Rudolph the Red-Nosed Reindeer";
 4:     char[] mfl = mostFamous.toCharArray();
 5:     for (int dex = 0; dex < mfl.length; dex++) {
 6:       char current = mfl[dex];
 7:       if (current != ' ') {
 8:         System.out.print(current);
 9:       } else {
10:         System.out.print('.');
11:       }
12:     }
13:   }
14: }

Compile and run this program using your Java development environment. The following commands can be used with the SDK:

javac NoSpaces.java
java NoSpaces

This program produces the following output:


The NoNames application stores the text Rudolph the Red-Nosed Reindeer in two places: a string called mostFamous, and a char array called mfl. The array is created in Line 4 by calling the toCharArray() method of mostFamous, which fills an array with one element for each character in the text. The character R goes into element 0, u into element 1, d into element 2, and so on, up to r in element 29.

The for loop in Lines 5–12 looks at each character in the mfl array. If the character is not a space, it is displayed. If it is a space, a . character is displayed instead.

  • + Share This
  • 🔖 Save To Your Account