[go: up one dir, main page]

0% found this document useful (0 votes)
57 views10 pages

Hour 6. Using Strings To Communicate

- Strings are commonly used in programming to store and present text to users. They allow computers to communicate. - In Java, strings are created using the String data type and stored in variables. Special characters can be included in strings using escape codes like \" for double quotes. - Strings can be displayed to users using System.out.println() or concatenated together using the + operator to combine strings, variables, and other data types into a single string.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views10 pages

Hour 6. Using Strings To Communicate

- Strings are commonly used in programming to store and present text to users. They allow computers to communicate. - In Java, strings are created using the String data type and stored in variables. Special characters can be included in strings using escape codes like \" for double quotes. - Strings can be displayed to users using System.out.println() or concatenated together using the + operator to combine strings, variables, and other data types into a single string.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Hour 6.

Using Strings to Communicate

In the film The Piano, Holly Hunter portrays Ada, a young Scottish woman who marries badly. A
mute since the age of six, 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 an essential need. (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 upper- 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 Java compiler 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. A string is denoted with double
quotation marks around the text in a Java statement. These quotation marks will not be
included in the string itself.
 Unlike the other types of variables you have used—int, float, char, boolean, and so on—the
name of 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 the material you
want to be displayed within the parentheses.
 Another way to display text is to call System.out.print(). This statement displays strings and
other variables inside the parentheses, but unlike System.out.println(),it allows subsequent
statements to display text on the same line.
 You can use System.out.print() several times in a row to display several things on the same
line, as in this example:
 System.out.print("She ");
 System.out.print("never ");
 System.out.print("said ");
 System.out.print("another ");
 System.out.println("word.");
 These statements cause the following text to be displayed:
 She never said another word.

 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 quotation marks are not
displayed, which brings up a good question: What if you want to display double quotation
marks?
 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 characters Display

\' Single quotation mark

\" Double quotation mark

\\ Backslash

\t Tab

\b Backspace

\r Carriage return

\f Formfeed

\n Newline
 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
cause 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 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.

 Advanced String Handling


 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 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 also 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 String's 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.
 Note that the toUpperCase() method does not change the case of the string variable it is called
on. In the preceding example, the baines variable will still be equal to Harvey Keitel.
 Looking for a String
 Another common task when handling strings is to see whether one string can be found inside
another. This is useful when you're looking for specific text in a large number of strings (or a
very large string).
 To look inside a string, use its indexOf() method. Put the string you are looking for inside the
parentheses. If the string is not found, indexOf() produces the value -1. If the string is found,
indexOf() produces an integer that represents the position where the string begins. Positions
in a string are numbered upwards from 0, beginning with the first character in the string. (In
the string "The Piano", the text "Piano" begins at position 3.)
 One possible use of the indexOf() method would be to search the entire script of The Piano
for the place where Ada's domineering husband tells her daughter Flora, "You are greatly
shamed and you have shamed those trunks."
 If the entire script of The Piano was stored in a string called script, you could search it for
part of that quote with the following statement.
 int position = script.indexOf("you have shamed those trunks");
 If that text can be found in the script string, position will equal the position at which the text
"you have shamed those trunks" begins. Otherwise, it will equal -1.
 Note
 The indexOf() method is case sensitive, which means that it only looks for text capitalized
exactly like the search string. If the string contains the same text capitalized differently,
indexOf() produces the value -1.

Workshop: Presenting Credits

In The Piano, 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.

Example 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, 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 who are 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 onscreen. 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 are either text or string variables that should be shown.

 Line 22 ends the main() block statement.

 Line 23 ends the program.

If you're using the SDK, you can attempt to compile the program by going to the folder 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 you find in your version of the Credits program
and try again to compile it.

Listing 6.2 shows the output of the Credits application: 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 of typing alone.

Example 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
Summary

Once your version of Credits works like the one shown in Listing 6.2, give yourself some credit, 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, 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.

You might also like