Page 121 - Introduction to Programming with Java: A Problem Solving Approach
P. 121
3.22 Strings 87 (Word, Excel, PowerPoint) all include text search and text replace capabilities. In this section, we describe
how Java provides that sort of string-manipulation functionality in the String class. String Concatenation
As you know, strings are normally concatenated with the + operator. Note that strings can also be concat- enated with the += compound assignment operator. In the following example, if the animal string refer- ences “dog” originally, it references “dogfish” after the statement is executed:
animal += "fish";
We recommend that you now go through a trace to make sure you thoroughly understand string concatenation. See the code fragment in Figure 3.10. Try to trace the code fragment on your own prior to looking at the solution.
Put yourself in computer’s place.
declaration
1
String s1;
2
String s2 = "and I say hello";
s1 = "goodbye";
s1 = "You say " + s1;
s1 += ", " + s2 + '.';
System.out.println(s1);
initialization
3
4
5
6
7
Apago PDF Enhancer
assignment
concatenation, then assignment
concatenation, then compound assignment
line#
s1
s2
output
1
?
2
and I say hello
4
goodbye
5
You say goodbye
6
you say goodbye, and I say hello.
7
You say goodbye, and I say hello.
Figure 3.10 Code fragment and associated trace for string concatenation illustration String Methods
In the previous section, we defined an object to be a collection of data. An object’s data is normally protected, and, as such, it can be accessed only through special channels. Normally, it can be accessed only through the object’s methods. A string object stores a collection of characters, and a string object’s characters can be ac- cessed only through its charAt method. In the remainder of this section, we’ll describe the charAt method as well as three other popular string methods—length, equals, and equalsIgnoreCase. These meth- ods, as well as many about other string methods, are defined in the String class.
If you’d like to learn more about the String class and all of its methods, visit Sun’s Get help from Java documentation Web site, http://java.sun.com/javase/6/docs/api/, and follow links that the source. take you to the String class.