Using Strings to Communicate - Learning the Basics of Programming - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part II: Learning the Basics of Programming

Hour 6. Using Strings to Communicate

THIS HOUR’S TO-DO LIST:

Image Use strings to store text.

Image Display strings in a program.

Image Include special characters in a string.

Image Paste two strings together.

Image Include variables in a string.

Image Compare two strings.

Image Determine the length of a string.

Your computer programs are capable of quietly doing their work and never stopping for a chat.

Java programs 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 learn all about working with strings.

Storing Text in Strings

Strings 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 = '@';

The value of the character must be surrounded by single quotation marks.

A string is a collection of characters. You can set up a variable to hold a string value by following String with the name of the variable, as in this statement:

String fullName = "Fin Shepard";

This statement creates a string variable called fullName containing the text “Fin Shepard,” the hero in the 2013 cinematic masterpiece Sharknado. A string is denoted with double quotation marks around the text in a Java statement. These quotation marks are not 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.

Strings are a special kind of information called objects, and the types of all objects are capitalized in Java. You learn about objects during Hour 10, “Creating Your First Object.” The important thing to note during this hour is that strings are different from the other variable types, and because of this difference, String is capitalized.

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 strings and other variables inside the parentheses and displays their values on the system output device, which is the computer’s monitor. Here’s an example:

System.out.println("We can't just wait here for sharks to rain down on us.");

This statement causes the following text to be displayed:

We can't just wait here for sharks to rain down on us.

Displaying text on the screen often is called printing, which is what println() stands for—print line. You can use the System.out.println() statement to display text within double quotation marks and also to display variables, as you see later. 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 enables 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("There's ");
System.out.print("a ");
System.out.print("shark ");
System.out.print("in ");
System.out.print("your ");
System.out.println("pool.");

These statements cause the following text to be displayed:

There's a shark in your pool.

Using Special Characters in Strings

When a string is being created or displayed, its text must be enclosed within double quotation marks. 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("Anthony Ferrante directed \"Sharknado\" in 2013.");

This code is displayed as the following:

Anthony Ferrante directed "Sharknado" in 2013.

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 (\).

Image

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("Script by\nThunder Levin");

This statement would be displayed like this:

Script by
Thunder Levin

Pasting Strings Together

When you use System.out.println() and work with strings in other ways, you can paste two strings together by using +, the same operator that is used to add numbers.


Note

You’ll probably see the term concatenation in other books as you build your programming skills, so it’s worth knowing. However, pasting is the term used here when one string and another string are joined together. Pasting sounds like fun. Concatenating sounds like something that should never be done in the presence of an open flame.


The + operator has a different meaning in relation to strings. Instead of performing some math, it pastes two strings together. This action can cause strings to be displayed together or make one big string out of two smaller ones.

Concatenation is the word used to describe this action because it means to link two things together.

The following statement uses the + operator to display a long string:

System.out.println("\"\'Sharknado\' is an hour and a half of your "
+ "life that you'll never get back.\nAnd you won't want to.\"\n"
+ "\t-- David Hinckley, New York Daily News");

Instead of putting this entire string on a single line, which would make it harder to understand when you look at the program later, you use the + operator to break the text over two lines of the program’s Java text file. When this statement is displayed, it appears as the following:

"'Sharknado' is an hour and a half of your life that you'll never get
back. And you won't want to."
-- David Hinckley, New York Daily News

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, you use it more often to link strings and variables. Take a look at the following:

int length = 86;
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: 86 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 86. It is displayed between the strings Running time: andminutes. 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 + "shark ";
searchKeywords = searchKeywords + "hurricane ";
searchKeywords = searchKeywords + "danger";

This code would result in the searchKeywords variable being set to “shark hurricane danger”. 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 thesearchKeywords variable equal to its current string plus the string “shark” added to the end. The next two lines add “hurricane” and “danger” 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: 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 statements:

String searchKeywords = "";
searchKeywords += "shark ";
searchKeywords += "hurricane ";
searchKeywords += "danger";

This code produces the same result: searchKeywords is set to “shark hurricane danger”.

Advanced String Handling

There are several other 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 use on other objects later.

Comparing Two Strings

One thing you are 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 = "chainsaw";
String guess = "pool cue";
System.out.println("Is Fin's favorite weapon a " + guess + "?");
System.out.println("Answer: " + favorite.equals(guess));

This example uses two different string variables. One, favorite, stores the name of Fin’s favorite shark-hunting instrument: a chainsaw. The other, guess, stores a guess as to what his favorite might be. The guess is that Fin prefers a pool cue.

The third line displays the text “Is Fin’s favorite weapon 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 has the same value as another. If the two string variables have the same value, the text true is displayed. If not, the text false is displayed. The following is the output of this example:

Output

Is Fin's favorite weapon a pool cue?
Answer: false

Determining the Length of a String

It also can be useful to determine the length of a string in characters. You do this with 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 = "Ben Demaree";
int nameLength = cinematographer.length();

This example sets nameLength, an integer variable, equal to 11. The cinematographer.length() method counts the number of characters in the string variable called cinematographer and stores this count in 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 Ian Ziering and the text IAN ZIERING refer to the same thing, most computers would disagree. The equals() method discussed previously in this hour would state authoritatively that “Ian Ziering” is not equal to “IAN ZIERING”.

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

String fin = "Ian Ziering";
String change = fin.toUpperCase();

This code sets the string variable change equal to the fin string variable converted to all uppercase letters—“IAN ZIERING”. The toLowerCase() method works in the same fashion but returns an all-lowercase string value.


Note

Another way to get around this particular obstacle is to call the equalsIgnoreCase() method, which compares two strings irrespective of capitalization. Calling that method to compare the string “Tara Reid” to “TARA REID” would return the value true to indicate they match.


Note that the toUpperCase() method does not change the case of the string variable it is called on. In the preceding example, the fin variable is still equal to “Ian Ziering”.

Looking for a String

Another common task when handling strings is to see whether one string can be found inside another. 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 “Sharknado”, the text “nado” begins at position 5.


Caution

The indexOf() and contains() methods are case sensitive, which means that they look only for text capitalized exactly like the search string. If the string contains the same text capitalized differently, indexOf() produces the value –1 and contains() returns false.


One possible use of the indexOf() method would be to search the entire script of Sharknado for the place where the heroes are flying a helicopter into a tornado to drop a bomb into it and Nova says, “We’re gonna need a bigger chopper.”

If the entire script of Sharknado was stored in a string called script, you could search it for part of that quote with the following statement.

int position = script.indexOf("We're gonna need a bigger chopper");

If that text can be found in the script string, position equals the position at which the text “We’re gonna need a bigger chopper” begins. Otherwise, it will equal –1.

If you are looking for one string inside another but don’t care about the position, a string’s contains() method returns a Boolean value. It is true if the looked-for string is found and false otherwise. Here’s an example:

if (script.contains("There's a shark in your pool")) {
int stars = 4;
}

Presenting Credits

Next, to reinforce the string-handling features that have been covered, you write a Java program to display credits for a feature film. You can probably guess the movie.

Return to the Java24 project in NetBeans and create a new empty Java file called Credits in the com.java24hours package. Enter the text of Listing 6.1 into the source editor and save the file when you’re done.

LISTING 6.1 The Credits Program


1: package com.java24hours;
2:
3: class Credits {
4: public static void main(String[] arguments) {
5: // set up film information
6: String title = "Sharknado";
7: int year = 2013;
8: String director = "Anthony Ferrante";
9: String role1 = "Fin";
10: String actor1 = "Ian Ziering";
11: String role2 = "April";
12: String actor2 = "Tara Reid";
13: String role3 = "George";
14: String actor3 = "John Heard";
15: String role4 = "Nova";
16: String actor4 = "Cassie Scerbo";
17: // display information
18: System.out.println(title + " (" + year + ")\n" +
19: "A " + director + " film.\n\n" +
20: role1 + "\t" + actor1 + "\n" +
21: role2 + "\t" + actor2 + "\n" +
22: role3 + "\t" + actor3 + "\n" +
23: role4 + "\t" + actor4);
24: }
25: }


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:

Image Line 3 gives the Java program the name Credits.

Image Line 4 begins the main() block statement in which all the program’s work gets done.

Image Lines 6–16 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.

Image Lines 18–23 are one long System.out.println() statement. Everything between the first parenthesis on Line 18 and the last parenthesis on Line 23 is displayed onscreen. The newline character (\n) causes the text after it to be displayed at the beginning of a new line. The tab character (\t) inserts tab spacing in the output. The rest are either text or string variables that should be shown.

Image Line 24 ends the main() block statement.

Image Line 25 ends the program.

If you do encounter error messages, correct any typos you find in your version of the Credits program and save it again. NetBeans compiles the program automatically. When you run the program, you see an output window like the Output pane in Figure 6.1.

Image

FIGURE 6.1 The output of the Credits program.

Summary

When your version of Credits looks like Figure 6.1, give yourself some credit. Six hours into this book, you’re writing longer Java programs and dealing with more sophisticated issues. Strings are something you use every time you sit down to write a program. You’ll be using strings in many ways to communicate with users.

Workshop

Q&A

Q. How can I set the value of a string variable to be blank?

A. Use an empty string, a pair of double quotation marks without any text between them. The following code creates a new string variable called georgeSays and sets it to nothing:

String georgeSays = "";

Q. I can’t seem to get the toUpperCase() method to change a string so that it’s all capital letters. What am I doing wrong?

A. When you call a String object’s toUpperCase() method, it doesn’t actually change the String object it is called on. Instead, it creates a new string that is set in all uppercase letters. Consider the following statements:

String firstName = "Baz";
String changeName = firstName.toUpperCase();
System.out.println("First Name: " + firstName);

These statements display the text “First Name: Baz” because firstName contains the original string. If you switched the last statement to display the changeName variable instead, it would output “First Name: BAZ”.

Strings do not change in value in Java after they are created.

Q. Do all methods in Java display true or false in the same way that the equals() method does in relation to strings?

A. Methods have different ways of producing a response after they are used. When a method sends back a value, as the equals() method does, it’s called returning a value. The equals() method is set to return a Boolean value. Other methods might return a string, an integer, another type of variable, or nothing at all—which is represented by void.

Q. Why do schools assign grades the letters A, B, C, D, and F but not E?

A. The letter grade E already was being used in an alternative grading system. Until the mid-20th century, in the United States the most popular grading system was to assign E for excellent, S for satisfactory, N for needs improvement, or U for the dreaded unsatisfactory. So when the ABCD system came along, giving a failing student an E was considered a not-so-excellent idea.

ESNU grading remains in wide use in elementary schools.

Quiz

The following questions test your knowledge of the care and feeding of a string.

1. My friend concatenates. Should I report him to the authorities?

A. No. It’s only illegal during the winter months.

B. Yes, but not until I sell the story to TMZ.com first.

C. No. All he’s doing is pasting two strings together in a program.

2. Why is the word String capitalized, whereas int and others are not?

A. String is a full word, but int ain’t.

B. Like all objects that are a standard part of Java, String has a capitalized name.

C. Poor quality control at Oracle.

3. Which of the following characters puts a single quotation mark in a string?

A. <quote>

B. \'

C. '

Answers

1. C. Concatenation is just another word for pasting, joining, melding, or otherwise connecting two strings together. It uses the + and += operators.

2. B. The types of objects available in Java are all capitalized, which is the main reason variable names have a lowercase first letter. It makes it harder to mistake them for objects.

3. B. The single backslash is what begins one of the special characters that can be inserted into strings.

Activities

You can review the topics of this hour more fully with the following activities:

Image Write a short Java program called Favorite that puts the code from this hour’s “Comparing Two Strings” section into the main() block statement. Test it out to make sure it works as described and says that Fin’s favorite shark-killing weapon is not the pool cue. When you’re done, change the initial value of the guess variable from “pool cue” to “chainsaw”. See what happens.

Image Modify the Credits program so the names of the director and all performers are displayed entirely in uppercase letters.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.