THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The concatenation operator can also be used in the short-hand += form, to assign the concatenation of the
original string and the given string, back to the original string reference. Here's an upgraded program:


class BetterStringsDemo {
public static void main(String[] args) {
String myName = "Petronius";
String occupation = "Reorganization Specialist";


myName += " Arbiter";


myName += " ";
myName += "(" + occupation + ")";
System.out.println("Name = " + myName);
}
}


Now when you run the program, you get this output:


Name = Petronius Arbiter (Reorganization Specialist)


String objects have a length method that returns the number of characters in the string. Characters are
indexed from 0 tHRough length()-1, and can be accessed with the charAt method, which takes an
integer index and returns the character at that index. In this regard a string is similar to an array of characters,
but String objects are not arrays of characters and you cannot assign an array of characters to a String
reference. You can, however, construct a new String object from an array of characters by passing the array
as an argument to a String constructor. You can also obtain an array of characters with the same contents as
a string using the toCharArray method.


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 object,
such as the += operation in BetterStringsDemo, you actually get a new read-only String object, while
the original String object remains unchanged. 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);

Free download pdf