Java Reference
In-Depth Information
safely pass immutable objects to a third-party library and expect that the objects will not be
modifed.
Of course, it may be possible to tinker with the
String
's internal data structures using the
Reflection API, as shown in
Accessing Private Methods and Fields via Reflection
,
but then
all bets are off. Secured environments, of course, do not permit access to the Reflection API.
Remember also that the
String
is a fundamental type in Java. Unlike most of the other
classes in the core API, the behavior of strings is not changeable; the class is marked
final
so it cannot be subclassed. So you can't declare your own
String
subclass. Think if you
could—you could masquerade as a
String
but provide a
setCharAt()
method! Again, they
thought of that. If you don't believe me, try it out:
public
public class
class
WolfInStringsClothing
WolfInStringsClothing
extends
extends
java
.
lang
.
String
{
//EXPECT COMPILE ERROR
public
public
void
char
newChar
) {
// The implementation of this method
// would be left as an exercise for the reader.
// Hint: compile this code exactly as is before bothering!
void
setCharAt
(
int
int
index
,
char
}
}
Got it? They thought of that!
Of course you do need to be able to modify strings. Some methods extract part of a
String
;
these are covered in the first few recipes in this chapter. And
StringBuilder
is an important
set of classes that deals in characters and strings and has many methods for changing the
contents, including, of course, a
toString()
method. Reformed C programmers should note
that Java strings are not arrays of chars as in C, so you must use methods for such operations
as processing a string one character at a time; see
Processing a String One Character at a