Difference between revisions of "Arrays of Strings"

From CompSciWiki
Jump to: navigation, search
m (Updated spacing of code.)
 
(35 intermediate revisions by 6 users not shown)
Line 1: Line 1:
{{Template:1010Topic|Chapter_TOC=[[More With Arrays]] > [[Arrays of Strings]]|Introduction=This section is all about arrays of Strings. This section assumes that you have already read the chapter on Strings and the chapter on Arrays. In addition to teaching you the basics of arrays with Strings, I'll talk about indexing errors (such as off-by-one errors) and how infuriating they can be when using arrays of Strings.|Overview=After reading this section, you will know:<br>1. What an array of Strings is<br>2. How arrays of Strings work<br>3. Using arrays of Strings<br>4. Gotchas unique to arrays of Strings}}
+
{{Template:1010Topic
 +
|Chapter_TOC=[[More With Arrays]] > [[Arrays of Strings]]
 +
|Previous=[[Partially Filled Arrays]]
 +
|Next=[[Searching Arrays]]
 +
|Body=
  
== What Are Arrays of Strings? ==
+
==Introduction==
 +
This chapter assumes that you have already read the chapter on [[Strings]] and the chapter on [[Arrays]].  This section includes what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to use String methods on an String Array indexes.
  
As said in the introduction, we are mainly assuming that you know what an [[Arrays|array]] is, and what a [[Strings|String]] is. As a quick refresher, an array is a contiguous group of some data type, and a String is effectively (if not actually) an array of characters. So, where is this going?
 
  
An array of Strings is a contiguous group of Strings, and each String is a contiguous group of characters. An array of strings is really a two-dimensional array: An array of arrays of characters. Even though you don't actually use Strings as arrays (for example, you get individual characters with charAt() instead of just an index), much of what you learn here will apply to real two-dimensional arrays. But that's for another course.
+
== What are Arrays of Strings? ==
  
 +
An array is a data structure whose indexes contain a specific data type.  A String is an object where text is represented as a list of characters. An array of Strings is an array where each index contains a String object.  Figure 1 displays an array of Strings containing brands of soft drinks.
  
== How Do Arrays of Strings Work? ==
+
[[Image:Arrays.Strings.Fig.1.jpg]]
  
Even though a few of the concepts presented here aren't ''exactly'' the same as real multi-dimensional arrays, they are very, very similar.
+
== Define and Initialize an Array of Strings ==
 +
You need to define an array of Strings before you can manipulate and process its contents.  All String objects in an array of Strings are initialized to the value null the array of Strings is initialized. Null is a special value that signifies that an object type currently has no value.  Figure 2 displays what our softDrinks array of Strings looked like when it was initialized.
  
We will begin with the first, big array "containing" each of these Strings. Here is where the definition of arrays as a contiguous "block" of a certain data type falls apart. The actual Strings being stored ''are not in this array'' -- Each of them is somewhere else in memory. Each slot of this big array just contains a number. This number is actually the memory address of the string that is "contained" in that array slot. This big array is an array of ''references'' to Strings. You will also learn about references in a later course, but for now, your Strings are accessed via those references. You will still work with your arrays of Strings as though they are contiguous groups of Strings, but note that they are really not contiguous groups of Strings.
+
{{CodeBlock
 +
|Code=
 +
String[] softDrinks;  // defines a String array named "softDrinks"
  
Now, we will look at each String. The definition of arrays as contiguous groups of data now comes in to affect. We don't have individual characters scattered throughout memory and an array of references to them making up the String -- We actually do have contiguous blocks of characters.
+
softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5
 +
}}
  
 +
[[Image:Arrays.Strings.Fig.2.jpg]]
  
== How Do I Use Arrays of Strings? ==
+
The code below displays how to define, initialize and access indexes of the array of Strings shown in figure 1.
  
Now that we have the brain-destroyingly confusing technical details of arrays of Strings out of the way, let's move on to actually using them. Using arrays of Strings is much, ''much'' simpler than trying to understand their low-level details. You declare them like any other, one-dimensional array:
+
{{CodeBlock
 +
|Code=
 +
public static void main(String[] args)
 +
{
 +
  // Option 1 for Defining, Initializing and Setting Contents
 +
  String[] softDrinks;  // defines a String array named "softDrinks"
  
<pre>String ouchMyFace[];</pre>
+
  softDrinks = new String[5]; // this initializes softDrinks to be an array of Size 5
  
Of course, the confusing part is that you actually have a two-dimensional array, but all of the "smaller" arrays are contained within the String type and  you do not have to worry about them. Huzzah!
+
  softDrinks[0] = "Coca Cola"; // sets index 0 of softDrinks to "Coca Cola"
 +
  softDrinks[1] = "Pepsi"; // sets index 1 of softDrinks to "Pepsi"
 +
  softDrinks[2] = "Dr. Pepper"; // sets index 2 of softDrinks to "Dr. Pepper"
 +
  softDrinks[3] = "Sprite"; // sets index 3 of softDrinks to "Sprite"
 +
  softDrinks[4] = "7up"; // sets index 4 of softDrinks to "7up"
 +
  softDrinks[5] = "Orange"; // sets index 5 of softDrinks to "Orange"
  
Anyway, you can get to your individual Strings in exactly the same way as you do with any other array. Observe:
+
  // Option 2 for Defining, Initializing and Setting Contents
 +
  String[] softDrinks2 = {"Coca Cola","Pepsi","Dr. Pepper","Sprite","7up","Orange");
 +
}
 +
}}
  
<pre>
 
String ouchMyFace[] = new String[5]; // Creates an array of 5 Strings -- These Strings are currently null, since they don't exist!
 
                                    // Again, you'll get to this in a later course, but note that there are no Strings here yet.
 
  
// So, let's make some Strings! Wheee!
+
== Using String Methods on Array Indexes ==
ouchMyFace[0] = "Ouch,";
+
Each index of an array of Strings contains a String object.  This means that all of the String methods you learned about can be applied to every index of an array of Strings. 
ouchMyFace[1] = "my";
+
ouchMyFace[2] = "face!";
+
ouchMyFace[3] = "It's";
+
ouchMyFace[4] = "on fire!";
+
  
// Now, let's print them. We'll assume you have seen loops.
+
Example 1: Print the length of every String in our SoftDrinks array (shown in Figure 1).
// Note: Length is a variable in the array that counts how many elements are present
+
{{CodeBlock
for( int i = 0; i < ouchMyFace.length; i++ )
+
|Code=
    System.out.print( ouchMyFace[i] + " " ); // Prints a space after each String
+
public printLength(String[] softDrinks)
</pre>
+
{
 +
  for (int i = 0; i < softDrinks.length; i++)
 +
  {
 +
      System.out.println("Length of the String ",softDrinks[i]," is ",softDrinks[i].length());
 +
  }
 +
}
 +
}}
 +
Notice how we accessed the array index "softDrinks[i]", then applied the "length()" method to it.  The length method was applied to every String object in our array softDrinks.  You can also apply other String methods such as charAt and subString to the String objects in array indexes.  Just remember to access the index of the String object first by using syntax like "softDrinks[i]".
  
The output of this little program will be the text "Ouch! My face! It's on fire! ". Note the space after the last exclamation point -- I am leaving it there because I am very lazy and it probably won't ever affect anything else.
 
  
Since your Strings are also arrays, you can also get at individual characters by using charAt(). Take this addition to our little program:
+
== Dealing with NULL Strings ==
  
<pre>
+
Figure 3 shows the array resulting from the code below.  Notice that there is a NULL value at index 4.  This NULL value exists because we didn't assign anything to the String object at index 4.
// Note: length() is a method in String that returns the number of characters in the String
+
for( int i = 0; i < ouchMyFace[0].length(); i++ )
+
    System.out.print( ouchMyFace[0].charAt[i] ); // Gives you each individual character
+
</pre>
+
  
This piece of code will print "Ouch,". Notice that there is no space at the end, since the original String had no spaces and we did not add any spaces.
+
{{CodeBlock
 +
|Code=
 +
public static void main(String[] args)
 +
{
 +
  String[] animals;  // defines a String array named "animals"
  
== What Should I Watch Out For? ==
+
  animals = new String[5];  // this initializes animals to be an array of Size 5
  
As already has been shown, using arrays of Strings is fairly easy. There are many things to watch out for, however.
+
  animals[0] = "Cat"; // sets index 0 of animals to "Cat"
 +
  animals[1] = "Dog"; // sets index 1 of animals to "Dog"
 +
  animals[2] = "Bat"; // sets index 2 of animals to "Bat"
 +
  animals[3] = "Bird"; // sets index 3 of animals to "Bird"
 +
  animals[5] = "Frog"; // sets index 5 of animals to "Frog"
 +
}
 +
}}
  
The first thing I would like to mention is that you need to understand how arrays of Strings work "under the hood". Yes, the low-level details of String arrays probably makes you want to scream and panic, but those concepts are critical to debugging programs that work with arrays of Strings.
+
[[Image:Arrays.Strings.Fig.3.jpg]]
  
The second thing I would like to mention is that the additional dimension adds much more work. When using an array, you must first make sure that the array has been created with the '''new''' keyword. When using a String, you must first make sure that the String has been created with '''new''' (or by assigning a String literal to a String variable). From these, when you work with an array of Strings, you must first create the array of Strings, then you must go through the array and create each individual String. Note the examples in the last section: I created the array with '''new''', but this did not give me any Strings. I needed to go through each element of this array and create a String manually. Trying to access an array that does not exist, or a String that does not exist, will cause your program to throw an exception and halt.
+
=== The Problem with NULL Values ===
  
<pre>
+
Let's print the contents of animals.
String letsCrashThis[];
+
  
// Accessing an array element that does not exist: CRASH
+
{{CodeBlock
letsCrashThis[5] = "An escalator cannot break. It can only become stairs.";
+
|Code=
 +
public print(String[] animals)
 +
{
 +
  for (int i=0; i < animals.length; i++)
 +
  {
 +
      System.out.println(animals[i]);
 +
  }
 +
}
 +
}}
  
// This would cause the last statement to work, if placed before
+
We will encounter a problem when printing this array when i=4, because the String object at animals[4] is NULL.  We can't print NULL, so our program will crash when i=4.
letsCrashThis = new String[6];
+
  
// Accessing a String that does not exist, even though the array does: CRASH
+
=== Fixing the NULL String Problem ===
System.out.println( letsCrashThis[3].charAt(0) );
+
</pre>
+
  
The third thing I would like to mention is that you must watch your indexes. The additional dimension also adds so much more potential for array indexing errors. Not only can you try to access an element outside of your array of Strings, you can also try to access a character outside of a given String. This can get really annoying; see below for an example...
+
We can fix our print method by testing for NULL values. The '==' and '!=' operators allow us to check each index to determine if it contains a NULL value or not. The code below shows off an improved version of our print method.
  
<pre>
+
{{CodeBlock
String moreCrashing[] = new String[10];
+
|Code=
 +
public print(String[] animals)
 +
{
 +
  for (int i=0; i < animals.length; i++)
 +
  {
 +
      if (animals[i] != NULL)
 +
      {
 +
        System.out.println(animals[i]);
 +
      }
 +
  }
 +
}
 +
}}
  
// Array off-by-one error: This accesses eleven elements, but the array has only ten!
+
When i=4 in our improved version, the if statement will evaluate and see that animals[4] == NULL and will not print.  Therefor, we avoid our program crashing like our previous print method.  The for loop will continue executing until the boolean i < animals2.length returns false.
// CRAAASSHH!
+
for( int i = 0; i <= 10; i++ )
+
    moreCrashing[i] = "Escalator Temporarily Stairs";
+
  
// Causes both array off-by-one errors AND String off-by-one errors
 
// Access characters that are not part of each String,
 
// AND an array element that is not part of the array!
 
// See how insidious this can get?
 
for( int i = 0; i <= 10; i++ )
 
    System.out.println( moreCrashing[i].charAt(1000) );
 
</pre>
 
  
This is all exactly why working with multi-dimensional arrays -- including arrays of Strings -- is so horrifying. Hopefully, this section has taught you to be especially vigilant when writing and debugging programs that work with arrays of Strings. If nothing else, at least you know to run screaming from any assignment that involves arrays of more than one dimension.
+
== Section Summary ==
  
--[[User:JonathanM|JonathanM]] 13:54, 27 November 2007 (CST)
+
Arrays of Strings are arrays where each index contains a String.  You can process many Strings at once by utilizing an array of Strings instead of declaring a lot of separate String objects.  All indexes within an array of Strings are initialized to NULL.  You can manually assign String values to an array index to overwrite the NULL value.  Be careful of NULL values when processing an array of Strings.  Use the '!=' and '==' operators to check each index of an array of Strings for a NULL value.  You are able to apply String methods to each index of an array of Strings.  Make sure you access the index before applying the method.  You now know what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to apply String methods to the indexes of an array of Strings.
 +
}}

Latest revision as of 23:34, 7 December 2011

COMP 1010 Home > More With Arrays > Arrays of Strings


Introduction

This chapter assumes that you have already read the chapter on Strings and the chapter on Arrays. This section includes what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to use String methods on an String Array indexes.


What are Arrays of Strings?

An array is a data structure whose indexes contain a specific data type. A String is an object where text is represented as a list of characters. An array of Strings is an array where each index contains a String object. Figure 1 displays an array of Strings containing brands of soft drinks.

Arrays.Strings.Fig.1.jpg

Define and Initialize an Array of Strings

You need to define an array of Strings before you can manipulate and process its contents. All String objects in an array of Strings are initialized to the value null the array of Strings is initialized. Null is a special value that signifies that an object type currently has no value. Figure 2 displays what our softDrinks array of Strings looked like when it was initialized.

 String[] softDrinks;  // defines a String array named "softDrinks"

softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5 

Arrays.Strings.Fig.2.jpg

The code below displays how to define, initialize and access indexes of the array of Strings shown in figure 1.

 public static void main(String[] args)
{
   // Option 1 for Defining, Initializing and Setting Contents
   String[] softDrinks;  // defines a String array named "softDrinks"

   softDrinks = new String[5];  // this initializes softDrinks to be an array of Size 5

   softDrinks[0] = "Coca Cola"; // sets index 0 of softDrinks to "Coca Cola"
   softDrinks[1] = "Pepsi"; // sets index 1 of softDrinks to "Pepsi"
   softDrinks[2] = "Dr. Pepper"; // sets index 2 of softDrinks to "Dr. Pepper"
   softDrinks[3] = "Sprite"; // sets index 3 of softDrinks to "Sprite" 
   softDrinks[4] = "7up"; // sets index 4 of softDrinks to "7up"
   softDrinks[5] = "Orange"; // sets index 5 of softDrinks to "Orange"

   // Option 2 for Defining, Initializing and Setting Contents
   String[] softDrinks2 = {"Coca Cola","Pepsi","Dr. Pepper","Sprite","7up","Orange");
} 


Using String Methods on Array Indexes

Each index of an array of Strings contains a String object. This means that all of the String methods you learned about can be applied to every index of an array of Strings.

Example 1: Print the length of every String in our SoftDrinks array (shown in Figure 1).

 public printLength(String[] softDrinks)
{
   for (int i = 0; i < softDrinks.length; i++)
   {
      System.out.println("Length of the String ",softDrinks[i]," is ",softDrinks[i].length());
   }
} 

Notice how we accessed the array index "softDrinks[i]", then applied the "length()" method to it. The length method was applied to every String object in our array softDrinks. You can also apply other String methods such as charAt and subString to the String objects in array indexes. Just remember to access the index of the String object first by using syntax like "softDrinks[i]".


Dealing with NULL Strings

Figure 3 shows the array resulting from the code below. Notice that there is a NULL value at index 4. This NULL value exists because we didn't assign anything to the String object at index 4.

 public static void main(String[] args)
{
   String[] animals;  // defines a String array named "animals"

   animals = new String[5];  // this initializes animals to be an array of Size 5

   animals[0] = "Cat"; // sets index 0 of animals to "Cat"
   animals[1] = "Dog"; // sets index 1 of animals to "Dog"
   animals[2] = "Bat"; // sets index 2 of animals to "Bat"
   animals[3] = "Bird"; // sets index 3 of animals to "Bird" 
   animals[5] = "Frog"; // sets index 5 of animals to "Frog"
} 

Arrays.Strings.Fig.3.jpg

The Problem with NULL Values

Let's print the contents of animals.

 public print(String[] animals)
{
   for (int i=0; i < animals.length; i++)
   {
      System.out.println(animals[i]);
   }
} 

We will encounter a problem when printing this array when i=4, because the String object at animals[4] is NULL. We can't print NULL, so our program will crash when i=4.

Fixing the NULL String Problem

We can fix our print method by testing for NULL values. The '==' and '!=' operators allow us to check each index to determine if it contains a NULL value or not. The code below shows off an improved version of our print method.

 public print(String[] animals)
{
   for (int i=0; i < animals.length; i++)
   {
      if (animals[i] != NULL)
      {
         System.out.println(animals[i]);
      }
   }
} 

When i=4 in our improved version, the if statement will evaluate and see that animals[4] == NULL and will not print. Therefor, we avoid our program crashing like our previous print method. The for loop will continue executing until the boolean i < animals2.length returns false.


Section Summary

Arrays of Strings are arrays where each index contains a String. You can process many Strings at once by utilizing an array of Strings instead of declaring a lot of separate String objects. All indexes within an array of Strings are initialized to NULL. You can manually assign String values to an array index to overwrite the NULL value. Be careful of NULL values when processing an array of Strings. Use the '!=' and '==' operators to check each index of an array of Strings for a NULL value. You are able to apply String methods to each index of an array of Strings. Make sure you access the index before applying the method. You now know what an array of Strings is, how to define and initialize an array of Strings, how to deal with null Strings and how to apply String methods to the indexes of an array of Strings.

Previous Page: Partially Filled Arrays Next Page: Searching Arrays