Session 9: Strings

The String class (Section 3.9)
    Creating strings
    String methods
    String operations
String-related methods
    The Integer.parseInt() method
    The IO.readString() and IO.readLine() methods
Equality testing (Section 4.1 (p 131))
Example

The String class

Textbook: Section 3.9

A string is a sequence of characters. It might represent a word, a sentence, or a name. They're extremely important to programming, and Java provides quite a bit of support for them.

Java implements strings as objects - the class name is String. Using strings is just like using other objects, except that Java also provides a little bit of additional syntax for dealing with strings, since they're so important.

Creating strings

To create a string, you don't even need to use the new keyword: You just enclose the string in double-quotes.

String name = "Carl";
If you want double-quotes, you can put the escape character (backslash) before them.
String shesaid = "\"Hello there,\" she said.";

The String class, by the way, is immutable - that is, the class provides no ways to modify the string once it's created. This distinguishes it from the Account class, which had a method (deposit()) that permitted you to alter its state. We would say that the Account class is mutable.

String methods

The String class provides a number of useful methods for working with strings. You can and should refer a complete list in the library documentation, but today we'll just touch on some of the more important.

int length()
Returns the number of characters in the string. If name holds the string ``Carl'', name.length() would return 4, since Carl is a four-letter word.

char charAt(int pos)
Returns the character that occurs at position pos in the string. Indexing begins at 0, so that if name holds the string ``Carl'', then name.charAt(2) refers actually to the third character of the string - 'r' in this case.

int indexOf(String to_find)
Returns the index where to_find first occurs in the string. For example, shesaid.indexOf("he") would be 8 (the location of the 'h' in there. If the to_find doesn't occur, it returns -1.

String substring(int begin, int end)
Extracts and returns a portion of the string, beginning at index begin and ending at (but not including) index end. For example, shesaid.substring(1, 6) would return ``Hello''.

String substring(int begin)
Extracts and returns the portion of the string beginning at index begin and going to the end of the string: name.substring(2) would return ``rl''.

String operations

Java provides a particularly simple operator for the very common operating of catenating two string together: the + operator.

IO.println(name + " Burch");
The result of the catenation here is the string ``Carl Burch,'' and that is what the above would display.

You can use numbers here also.

IO.println("i holds " + i);
If i is an int variable, the above would print the current value held by i, in decimal form.

Notice that Java uses + for both addition and catenation. Usually, this causes no confusion, but occassionally it's problematic. Consider the following example.

IO.println("i+1 = " + i+1);
If i held 2, this would actually print ``i+1 = 21''. This is because the + operator works left-to-right, so the above is identical to
IO.println(("i+1 holds " + i) + 1);

String-related methods

The Integer.parseInt() method

Another useful method to know about is the parseInt() class method in the Integer class. It takes a String as a parameter and returns the corresponding integer value.

int value = Integer.parseInt("563");
This puts the value 563 into the value variable.

There's also a Double.parseDouble() method that works the same way, except for double values.

The IO.readString() and IO.readLine() methods

The IO class provides two ways of reading a string from the user. The IO.readLine() method returns a string containing all the letters of a line, while the IO.readString() method returns the next word. (Actually, IO.readString() returns the next string of non-whitespace characters it finds - so the word can contain a mix of letters, digits, and punctuation.)

Equality testing

Textbook: Section 4.1 (p 131)

Last time we spoke about assignments with objects, and how when you assign an object to a variable, you are really copying a reference into the variable, not copying the object itself. As a result, you can have two variables copied into the same object.

This has important consequences when you want to compare two object values: You are comparing references, not the objects themselves. You might be tempted to write the following.

String name = IO.readLine();
if(name == "Carl") IO.println("Hello, professor"); // bad!!
This won't do what you want, however. Even if the user types ``Carl'', the program points name to a new String object containing the word Carl; this will be a different object than the other String object created by the double-quotes, which happens to contain the word Carl also. As a result, ``Hello, professor'' won't be printed.

The answer is to use the equals() method. This is defined for String objects to compare the letters of the string (not the references to the objects). So we should have written the above as:

String name = IO.readLine();
if(name.equals("Carl")) IO.println("Hello, professor");

Example

Say we want a program that finds the longest common prefix of two strings? For example, the longest prefix common to both CAROLING and CAROB is CARO.

We might do this using the following.

import csbsju.cs160.*;

public class Example {
    public static void run() {
        IO.println("Type two strings.");
        String a = IO.readString();
        String b = IO.readString();

        for(int i = 0; ; i++) {
            if(a.charAt(i) != b.charAt(i)) {
                IO.println("Prefix is " + a.substring(0, i));
                break;
            }
        }
    }
}
This program compiles fine. And if I ran it, I would get the following. (User input in boldface.)
Type two strings.
CAROLING CAROB
Prefix is CARO
This is the correct behavior.

And yet the program doesn't always work correctly? What's wrong, and how can you fix it?