Difference between revisions of "Arrays of Strings"

From CompSciWiki
Jump to: navigation, search
m (small edits)
(How do I use arrays of Strings?)
Line 16: Line 16:
  
 
<pre>
 
<pre>
String ouchMyFace[] = new String[5]; // Creates an array of 5 Strings -- These Strings are initialized to null.
+
String[] ouchMyFace = new String[5]; // Creates an array of 5 Strings -- These Strings are initialized to null.
  
 
// So, let's make some Strings!
 
// So, let's make some Strings!
Line 26: Line 26:
  
 
// Now, let's print them.
 
// Now, let's print them.
// Note: length is a variable in the array that keeps track of the number of elements
+
for( int i = 0; i < ouchMyFace.length; i++ ) {
for( int i = 0; i < ouchMyFace.length; i++ )
+
 
     System.out.print( ouchMyFace[i] + " " ); // Prints a space after each String
 
     System.out.print( ouchMyFace[i] + " " ); // Prints a space after each String
 +
}
 
</pre>
 
</pre>
  
Line 37: Line 37:
 
<pre>
 
<pre>
 
// Note: length() is a method in String that returns the number of characters in the String
 
// 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++ )
+
for( int i = 0; i < ouchMyFace[0].length(); i++ ) {
 
     System.out.print( ouchMyFace[0].charAt[i] ); // Gives you each individual character
 
     System.out.print( ouchMyFace[0].charAt[i] ); // Gives you each individual character
 +
}
 
</pre>
 
</pre>
  

Revision as of 02:36, 17 December 2008

COMP 1010 Home > 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. It will introduce you to arrays of Strings, show you how to use them, give you some tips of things to watch out for, and give you an idea of how they are stored.

   

{{{Body}}}

What are arrays of Strings?

Recall that an array is a contiguous group of some data type, and a String is text represented as a list of characters. An array of Strings, then, is a contiguous group of Strings, each of which contains text.

Also recall that a String is an object type, not a primitive type. That means that a String is represented by a reference that points to a value in memory. So, unlike arrays of primitive value types (like int, char, etc.) a String array is an array of references.

How do I use arrays of Strings?

String arrays are declared like any other array:

String[] ouchMyFace;

You can access individual Strings in exactly the same way as you do with any other array. Observe:

String[] ouchMyFace = new String[5]; // Creates an array of 5 Strings -- These Strings are initialized to null.

// So, let's make some Strings!
ouchMyFace[0] = "Ouch,";
ouchMyFace[1] = "my";
ouchMyFace[2] = "face!";
ouchMyFace[3] = "It's";
ouchMyFace[4] = "on fire!";

// Now, let's print them.
for( int i = 0; i < ouchMyFace.length; i++ ) {
    System.out.print( ouchMyFace[i] + " " ); // Prints a space after each String
}

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 -- we could add additional code to fix this, if necessary.

Since Strings contain more than one character, you can also get at individual characters by using charAt(). Observe the next part of our example program:

// 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
}

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.

What should I watch out for?

null Strings

The first "gotcha" is that all Strings in an array of Strings is initialized to the value null. Null is a special value that means that a variable of an object type currently has no value; that is, its reference points to nothing. Null is not a valid String, so you must use '==' and '!=' to check for it, rather than the .equals() method, like in this example:

String[] testing = new String[2];

testing[0] = "Not null!";

if (testing[0] == null) {
  System.out.println("testing[0] is null");
}
if (testing[1] == null) {
  System.out.println("testing[1] is null");
}

The output will be "testing[1] is null".

Calling any method on a String that does not point to a valid value (i.e. is null) will crash your program. The following program shows you what not to do:

String[] letsCrashThis = new String[5];

// Calling a method on a string that doesn't exist (i.e. is null)
System.out.println( letsCrashThis[3].charAt(0) );

The output will be a run-time error.

Nested for loops

A String stores multiple characters, so unlike other arrays, we often need nested for loops when dealing with arrays of Strings.

Observe the difference between two methods that accomplish the same goal: counting the number of 'a' characters in an array.

In the first example, we are dealing with a character array.

public static int countNumberOfAs(char[] charArray) {
  int count = 0;

  for (int i=0; i < charArray.length; i++) {
    if (charArray[i] == 'a') {
      count++;
    }
  }

  return count;
}

In the second example, we are dealing with a String array.

public static int countNumberOfAs(String[] stringArray) {
  int count = 0;

  for (int i=0; i < stringArray.length; i++) {

    for (int j=0; j < stringArray[i].length(); j++) {
      if (stringArray[i].charAt(j) == 'a') {
        count++;
      }
    }

  }

  return count;
}

Notice the addition nested for loop in the second example. When you are dealing with arrays of strings, you will often need nested loops like this because you have to deal with the characters in each String.

How do arrays of Strings work?

The actual Strings being stored are not in the array -- each of them is somewhere else in memory. Each element of the String array contains a reference that points to where the actual Strings are stored. You will still work with your arrays of Strings as though they are contiguous groups of Strings, but keep in mind that the elements of the array are references, not actual values.

SIDENOTE: Two-dimensional arrays

The following information is not tested, but may help you understand arrays of Strings, and will be relevant to future computer science courses.

In Java and many other programming languages, Strings are stored as arrays of characters. That means that when you create an array of Strings, you are really creating an array of arrays of characters.

That's a bit of a mouthful; here is what it would look like in code:

// An array of 5 characters
char[] charArray = new char[5];

// An array of 10 Strings
String[] stringArray = new String[10];

// An array of 10 arrays of 5 characters (in many ways the same as an array of 10 Strings)
char[][] char2DArray = new char[10][5];

A variable declared with two sets of square brackets ( [] ) like above is called a two-dimensional array. It is often used when dealing with information that makes sense as a matrix rather than a linear array.