Advanced String Handling InJava


In addition to creating strings, pasting them together, and using them with other types of variables, there are several different ways you can examine a string variable and change its value. These advanced features are possible because strings are objects in the Java language. Working with strings develops skills that you'll be using to work with other objects later.

Comparing Two Strings

One thing you will be testing often in your programs is whether one string is equal to another. You do this by using equals() in a statement with both of the strings, as in this example:

String favorite = "piano";

String guess = "ukelele";

System.out.println("Is Ada's favorite instrument a " + guess + "?");

System.out.println("Answer: " + favorite.equals(guess));

This example uses two different string variables. One, favorite, is used to store the name of Ada's favorite instrument: a piano. The other, guess, is used to store a guess as to what her favorite might be. The guess is that Ada prefers the ukelele.

The third line displays the text Is Ada's favorite instrument a followed by the value of the guess variable and then a question mark. The fourth line displays the text Answer: and then contains something new:

favorite.equals(guess)

This part of the statement is known as a method. A method is a way to accomplish a task in a Java program. This method's task is to determine if one string, favorite, has the same value as another string, guess. If the two string variables have the same value, the text true will be displayed. If not, the text false will be displayed. The following is the output of this example:

Is Ada's favorite instrument a ukelele?

Answer: false

Determining the Length of a String

It can be useful at times to determine the length of a string in characters. You do this by using the length() method. This method works in the same fashion as the equals() method, except that only one string variable is involved. Look at the following example:

String cinematographer = "Stuart Dryburgh";

int nameLength = cinematographer.length();

This example sets nameLength, an integer variable, equal to 15. The cinematographer.length() method counts the number of characters in the string variable called cinematographer, and this count is assigned to the nameLength integer variable.

Changing a Strings Case

Because computers take everything literally, it's easy to confuse them. Although a human would recognize that the text Harvey Keitel and the text HARVEY KEITEL are referring to the same thing, most computers would disagree. For instance, the equals() method discussed previously in this hour would state authoritatively that Harvey Keitel is not equal to HARVEY KEITEL.

To get around some of these obstacles, Java has methods that display a string variable as all uppercase letters (toUpperCase()) or all lowercase letters (toLowerCase()). The following example shows the toUpperCase() method in action:

String baines = "Harvey Keitel";

String change = baines.toUpperCase();

This code sets the string variable change equal to the baines string variable converted to all uppercase letters--HARVEY KEITEL, in other words. The toLowerCase() method works in the same fashion but returns an all-lowercase string value.

Workshop: Presenting Credits

Ada McGrath Stewart was thrown into unfamiliar territory when she moved from Scotland to New Zealand to marry a stranger who didn't appreciate her ivory tickling. You might have felt similarly lost with some of the topics introduced during this hour.

As a workshop to reinforce the string handling features that have been covered, you will write a Java program to display credits for a feature film. You have three guesses as to the movie chosen, and if you need a hint, it starts with a The and ends with a musical instrument that can be used to express the repressed passion of attractive mutes.

Load the word processor you're using to write Java programs and create a new file called Credits.java. Enter the text of Listing 6.1 into the word processor and save the file when you're done.

Listing 6.1. The Credits program.

 

 1: class Credits {

 2:      public static void main(String[] arguments) {

 3:          // set up film information

 4:          String title = "The Piano";

 5:          int year = 1993;

 6:          String director = "Jane Campion";

 7:          String role1 = "Ada";

 8:          String actor1 = "Holly Hunter";

 9:          String role2 = "Baines";

10:          String actor2 = "Harvey Keitel";

11:          String role3 = "Stewart";

12:          String actor3 = "Sam Neill";

13:          String role4 = "Flora";

14:          String actor4 = "Anna Paquin";

15:          // display information

16:          System.out.println(title + " (" + year + ")\n" +

17:                      "A " + director + " film.\n\n" +

18:                      role1 + "\t" + actor1 + "\n" +

19:                      role2 + "\t" + actor2 + "\n" +

20:                      role3 + "\t" + actor3 + "\n" +

21:                      role4 + "\t" + actor4);

22:     }

23: }


Before you attempt to compile the program with the javac tool, look over the program and see whether you can figure out what it's doing at each stage. Here's a breakdown of what's taking place:

·         Line 1 gives the Java program the name Credits.

·         Line 2 begins the main() block statement in which all of the program's work gets done.

·         Line 3 is a comment statement explaining that you're going to set up the film's information in subsequent lines.

·         Lines 4-14 set up variables to hold information about the film, its director, and its stars. One of the variables, year, is an integer. The rest are string variables.

·         Line 15 is another comment line for the benefit of humans like us examining the program.

·         Lines 16-21 are one long System.out.println() statement. Everything between the first parenthesis on Line 16 and the last parenthesis on Line 21 is displayed on-screen. The newline text (\n) causes the text after it to be displayed at the beginning of a new line. The Tab text (\t) inserts Tab spacing in the output. The rest is either text or string variables that should be shown.

·         Line 22 ends the main() block statement.

·         Line 23 ends the program.

Attempt to compile the program by going to the directory that contains Credits.java and typing this command:

javac Credits.java

If you do not see any error messages, the program has compiled successfully, and you can run it with the following command:

java Credits

If you do encounter error messages, correct any typos that you find in your version of the Credits program and try again to compile it.

Listing 6.2 shows the output of the Credits program: a rundown of the film, year of release, director, and the four lead performers from The Piano. Be glad that you didn't have to present the credits for an ensemble film. A program detailing Robert Altman's Short Cuts, the 1993 film with more than 25 lead characters, could hog an hour on typing alone.

Listing 6.2. The output of the Credits program.

 

The Piano 1993

A Jane Campion film.

Ada       Holly Hunter

Baines    Harvey Keitel

Stewart   Sam Neill

Flora Anna Paquin

If this hour's trivia related to The Piano and the films of director Jane Campion has sparked your curiosity, or if you just dig quiet women in braids, visit the following World Wide Web sites: n Magnus Hjelstuen's unofficial The Piano Web site, with cast descriptions, storyline discussion, and comprehensive details about his favorite movie:

                                           <http://www.ifi.uio.no/~magnush/Piano/>

n The Internet Movie Database, a voluminous yet searchable database of movies, TV shows, actors, directors, yet other related topics:

                                           <http://www.imdb.com>

Summary

Once your version of Credits works like the one shown in Listing 6.2, give yourself some credits, too. You're writing longer Java programs and dealing with more sophisticated issues each hour. Like variables, strings are something you'll use every time you sit down to write a program.

At the beginning of The Piano, Holly Hunter's Ada lost her piano when her new husband refused to make his Maori laborers carry it home. Luckily for you, the ability to use strings in your Java programs cannot be taken away by an insensitive newlywed or anyone else. You'll be using strings in many ways to communicate with users.

Post a Comment

Previous Post Next Post