Java Reference
In-Depth Information
strings. It must be made clear, however, that
String
reference variables may, of course,
change the object to which they refer. It is just that the contents of a specific
String
object
cannot be changed after it is created.
Ask the Expert
Q
:
You say that once created
, String
objects are immutable. I understand that, from
a practical point of view, this is not a serious restriction, but what if I want to
create a string that can be changed?
A
:
You're in luck. Java offers a class called
StringBuffer
, which creates string objects
that can be changed. For example, in addition to the
charAt( )
method, which obtains
the character at a specific location,
StringBuffer
defines
setCharAt( )
, which sets a
character within the string. Java also supplies
StringBuilder
, which is related to
StringBuffer
, and also supports strings that can be changed. However, for most pur-
poses you will want to use
String
, not
StringBuffer
or
StringBuilder
.
To fully understand why immutable strings are not a hindrance, we will use another of
String
's methods:
substring( )
. The
substring( )
method returns a new string that contains
a specified portion of the invoking string. Because a new
String
object is manufactured
that contains the substring, the original string is unaltered, and the rule of immutability re-
mains intact. The form of
substring( )
that we will be using is shown here:
String substring(int
startIndex
, int
endIndex
)
Here,
startIndex
specifies the beginning index, and
endIndex
specifies the stopping point.
Here is a program that demonstrates
substring( )
and the principle of immutable strings: