Java Reference
In-Depth Information
variable, after you have declared it, by using an assignment. For example, you can change the value of the
String variable myString to the following statement:
myString = "Strings can be knotty";
The effect of this is illustrated in Figure 4-6 .
The String object itself is distinct from the variable you use to refer to it. In the same way as you saw
with array objects, the variable myString stores a reference to a String object, not the object itself, so in
other words, a String variable records where the String object is in memory. When you declare and ini-
tialize myString , it references the object corresponding to the initializing string literal. When you execute
the assignment statement, the original reference is overwritten by the reference to the new string and the old
string is discarded. The variable myString then contains a reference to the new string.
String objects are said to be immutable — which just means that they cannot be changed. This means
that you cannot extend or otherwise modify the string that an object of type String represents. When you
execute a statement that combines existing String objects, you are always creating a new String object as
a result. When you change the string referenced by a String variable, you throw away the reference to the
old string and replace it with a reference to a new one. The distinction between a String variable and the
string it references is not apparent most of the time, but you see situations later in this chapter where it is
important to understand this, so keep it in mind.
You should also keep in mind that characters in a string are Unicode characters, so each one typically
occupies 2 bytes, with the possibility that they can be 4 bytes if you are using characters represented as sur-
rogates. This is also not something you need worry about most of the time, but there are occasions where
you need to be conscious of that, too.
Of course, you can declare a variable of type String without initializing it:
String anyString; // Uninitialized String variable
The anyString variable that you have declared here does not refer to anything. However, if you try to
compile a program that attempts to use anyString before it has been initialized by some means, you get an
error. If you don't want a String variable to refer to anything at the outset — for example, if you may or
Search WWH ::

Custom Search