Java Reference
In-Depth Information
Chapter 3. Strings and Things
Introduction
Character strings are an inevitable part of just about any programming task. We use them for
printing messages for the user; for referring to files on disk or other external media; and for
people's names, addresses, and affiliations. The uses of strings are many, almost without
number (actually, if you need numbers, we'll get to them in Chapter 5 ) .
If you're coming from a programming language like C, you'll need to remember that String
is a defined type (class) in Java—that is, a string is an object and therefore has methods. It is
not an array of characters (though it contains one) and should not be thought of as an array.
Operations like fileName.endsWith(".gif") and extension.equals(".gif") (and the
equivalent " .gif".equals(extension) ) are commonplace.foonote:[They are “equivalent”
with the exception that the first can throw a NullPointerException while the second can-
not.]
Notice that a given String object, once constructed, is immutable. In other words, once I
have said String s = " Hello " + yourName; , the contents of the particular object that refer-
ence variable s refers to can never be changed. You can assign s to refer to a different string,
even one derived from the original, as in s = s.trim() . And you can retrieve characters
from the original string using charAt() , but it isn't called getCharAt() because there is not,
and never will be, a setCharAt() method. Even methods like toUpperCase() don't change
the String ; they return a new String object containing the translated characters. If you need
to change characters within a String , you should instead create a StringBuilder (possibly
initialized to the starting value of the String ), manipulate the StringBuilder to your
heart's content, and then convert that to String at the end, using the ubiquitous toString()
method. [ 12 ]
How can I be so sure they won't add a setCharAt() method in the next release? Because the
immutability of strings is one of the fundamentals of the Java Virtual Machine. Immutable
objects are generally good for software reliability (some languages do not allow mutable ob-
jects). Immutability avoids conflicts, particularly where multiple threads are involved, or
where software from multiple organizations has to work together; for example, you can
 
Search WWH ::




Custom Search