Java Reference
In-Depth Information
String objects are read-only, or immutable: The contents of a String
never change. When you see statements like
str = "redwood";
// ... do something with str ..
str = "oak";
the second assignment gives a new value to the variable str , which is
an object reference to a different string object with the contents "oak" .
Every time you perform operations that seem to modify a String ob-
ject, such as the += operation in BetterStringsDemo , you actually get a
new read-only String object, while the original String object remains un-
changed. The classes StringBuilder and StringBuffer provide for mutable
strings and are described in Chapter 13 , where String is also described
in detail.
The equals method is the simplest way to compare two String objects to
see whether they have the same contents:
if (oneStr.equals(twoStr))
foundDuplicate(oneStr, twoStr);
Other methods for comparing subparts of strings or ignoring case dif-
ferences are also covered in Chapter 13 . If you use == to compare the
string objects, you are actually comparing oneStr and twoStr to see if
they refer to the same object, not testing if the strings have the same
contents.
Exercise 1.11 : Modify the StringsDemo application to use different
strings.
Exercise 1.12 : Modify ImprovedFibonacci to store the String objects it
creates into an array instead of invoking println with them directly.
 
Search WWH ::




Custom Search