In the film The Piano, Holly Hunter portrays Ada, a young Scottish woman who marries badly. A mute since the age of 6, Ada can only express herself fully by playing her prized possession, a piano. Like Ada, your computer programs are capable of quietly doing their work and never stopping for a chat--or piano recital--with humans. However, if The Piano teaches us anything, it is that communication ranks up there with food, water, and shelter as essential needs. (It also teaches us that Harvey Keitel has a lot of body confidence, but that's a matter for another book.)
Java programs don't have access to a piano. They use strings as the primary means to communicate with users. Strings are collections of text--letters, numbers, punctuation, and other characters. During this hour, you will learn all about working with strings in your Java programs. The following topics will be covered:
· Using strings to store text
· Displaying strings in a program
· Including special characters in a string
· Pasting two strings together
· Including variables in a string
· Some uses for strings
· Comparing two strings
· Determining the length of a string
· Changing a string to uppercase or lowercase
Storing Text in Strings
Strings are a common feature in computer programming because they provide a way to store text and present it to users. The most basic element of a string is a character. A character is a single letter, number, punctuation mark, or other symbol.
In Java programs, a character is one of the types of information that can be stored in a variable. Character variables are created with the char type in a statement such as the following:
char keyPressed;
This statement creates a variable named keyPressed that can store a character. When you create character variables, you can set them up with an initial value, as in the following:
char quitKey = `@';
Note that the value of the character must be surrounded by single quotation marks. If it isn't, the javac compiler tool will respond with an error when the program is compiled.
A string is a collection of characters. You can set up a variable to hold a string value by using the String text and the name of the variable, as in the following statement:
String fullName = "Ada McGrath Stewart";
This statement creates a String variable called fullName and stores the text Ada McGrath Stewart in it, which is the full name of Hunter's pianist. In a Java statement, a string is denoted with double quotation marks around the text. These quote marks will not be included in the string itself.
Unlike the other types of variables that you have used--int, float, char, boolean, and so on--the String type is capitalized. The reason for this is that strings are somewhat different than the other variable types in Java. Strings are a special resource called objects, and the types of all objects are capitalized. You'll be learning about objects during Hour 10, "Creating Your First Object." The important thing to note during this hour is that strings are different than the other variable types, and because of this difference, String is capitalized when strings are used in a statement.
Displaying Strings in Programs
The most basic way to display a string in a Java program is with the System.out.println() statement. This statement takes any strings and other variables inside the parentheses and displays them. The following statement displays a line of text to the system output device, which is the computer's monitor:
System.out.println("Silence affects everyone in the end.");
The preceding statement would cause the following text to be displayed:
Silence affects everyone in the end.
Displaying a line of text on the screen is often called printing, which is what println() stands for--"print this line." You can use the System.out.println() statement to display text within double quotation marks and also to display variables, as you will see. Put all material that you want to be displayed within the parentheses.
Using Special Characters in Strings
When a string is being created or displayed, its text must be enclosed within double quotation marks to indicate the beginning and end of the string. These quote marks are not displayed, which brings up a good question: What if you want to display double quotation marks?
In order to display them, Java has created a special code that can be put into a string: \". Whenever this code is encountered in a string, it is replaced with a double quotation mark. For example, examine the following:
System.out.println("Jane Campion directed \"The Piano\" in 1993.");
This code is displayed as the following:
Jane Campion directed "The Piano" in 1993.
You can insert several special characters into a string in this manner. The following list shows these special characters; note that each is preceded by a backslash (\).
Special charactersDisplay\'Single quotation mark\"Double quotation mark\\Backslash\tTab\bBackspace\rCarriage return\fFormfeed\nNewline
The newline character causes the text following the newline character to be displayed at the beginning of the next line. Look at this example:
System.out.println("Music by\nMichael Nyman");
This statement would be displayed as the following:
Music by
Michael Nyman
Pasting Strings Together
When you use the System.out.println() statement and handle strings in other ways, you will sometimes want to paste two strings together. You do this by using the same operator that is used to add numbers: +.
The + operator has a different meaning in relation to strings. Instead of trying to do some math, it pastes two strings together. This action can cause strings to be displayed together, or it can make one big string out of two smaller ones. Concatenation is a word used to describe this action, because it means to link two things together. You'll probably see this term in other books as you build your programming skills, so it's worth knowing. However, pasting is the term used here to describe what happens when one string and another string decide to get together. Pasting sounds like fun. Concatenating sounds like something that should never be done in the presence of an open flame.
The following statement uses the + operator to display a long string:
System.out.println("\"\'The Piano\' is as peculiar and haunting as any film " +
"I've seen.\"\n\t-- Roger Ebert, \'Chicago Sun-Times\'");
Instead of putting this entire string on a single line, which would make it harder to understand when you look at the program later, the + operator is used to break up the text over two lines of the program's Java text file. When this statement is displayed, it will appear as the following:
"`The Piano' is as peculiar and haunting as any film I've seen."
-- Roger Ebert, `Chicago Sun-Times'
Several special characters are used in the string: \", \', \n, and \t. To better familiarize yourself with these characters, compare the output with the System.out.println() statement that produced it.
Using Other Variables with Strings
Although you can use the + operator to paste two strings together, as demonstrated in the preceding section, you will use it more often to link strings and variables. Take a look at the following:
int length = 121;
char rating = `R';
System.out.println("Running time: " + length + " minutes");
System.out.println("Rated " + rating);
This code will be displayed as the following:
Running time: 121 minutes
Rated R
This example displays a unique facet about how the + operator works with strings. It can allow variables that are not strings to be treated just like strings when they are displayed. The variable length is an integer set to the value 121. It is displayed between the strings Running time: and minutes. The System.out.println() statement is being asked to display a string plus an integer plus another string. This statement works because at least one part of the group is a string. The Java language offers this functionality to make displaying information easier.
One thing that you might want to do with a string is paste something to it several times, as in the following example:
String searchKeywords = "";
searchKeywords = searchKeywords + "drama ";
searchKeywords = searchKeywords + "romance ";
searchKeywords = searchKeywords + "New Zealand ";
This code would result in the searchKeywords variable being set to drama romance New Zealand. The first line creates the searchKeywords variable and sets it to be an empty string because there's nothing between the double quotation marks. The second line sets the searchKeywords variable equal to its current string plus the string drama added to the end. The next two lines add romance and New Zealand in the same way.
As you can see, when you are pasting more text at the end of a variable, the name of the variable has to be listed twice. Java offers a shortcut to simplify this process a bit: the += operator. The += operator combines the functions of the = and + operators. With strings, it is used to add something to the end of an existing string. The searchKeywords example can be shortened by using +=, as shown in the following code:
String searchKeywords = "";
searchKeywords += "drama ";
searchKeywords += "romance ";
searchKeywords += "New Zealand ";
This code produces the same result: searchKeywords is set to drama romance New Zealand.
Post a Comment