Lecture 10

Strings

A string is a sequence of characters.  In Java, strings are represented by objects that are instances of the java.lang.String class.

Example:

String s = "Cat";
System.out.println(s);

Immutability

Like other classes, the String class has many methods that can be called on String objects.  For example, the replace method replaces all occurrences of one character with another.  Here is an example of calling the replace method on a string object.  Note that this code example contains an error, that will be explained shortly:

// Warning: this code has a bug
String s = "Cat";
s.replace('C', 'B');
System.out.println(s);

Since we are replacing all occurrences of the character 'C' with 'B', you would expect that the output of the call to println would be "Bat".  However, it instead prints "Cat", the original string value.  (Try it in DrJava and see for yourself.)  So, why does this happen?

The reason for this possibly-unexpected behavior is that the String class is immutable, which means that once a String object is created, its value (the string of characters it represents) never changes.  Methods like replace that modify a string value operate by constructing a new String object to represent the result string.  Here is the correct way to use the replace method:

String s = "Cat";
String s2 = s.replace('C', 'B');
System.out.println(s2);

This code prints "Bat" as expected.

length and charAt

Two useful operations on string values are

  1. Finding out the number of characters in the string
  2. Accessing a particular character in the string

These operations are performed by the length and charAt methods, respectively.  The characters in a string are indexed so that the first character in the string has index 0, and the index of the last character in the string has an index one less than the value returned by the length method.  As an example, the following code reads tokens (strings) using a scanner and prints out both the length of the string and each individual character in the string:

Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
  String token = keyboard.next();
  System.out.println(token + " has " + token.length() + " characters");
  for (int i = 0; i < token.length(); i++) {
    char c = token.charAt(i);
    System.out.println(c);
  }
}

Here's an example of this code running (user input in bold):

Beware, I live!
Beware, has 7 characters
B
e
w
a
r
e
,
I has 1 characters
I
live! has 5 characters
l
i
v
e
!

The String class has lots of other useful methods.  Check the Java API Documentation for more details.  (Look in the java.lang package, then chooes the String class.)