Java Reference
In-Depth Information
This declares the variable myString as type String , and initializes it with the value " My inaugural
string ". You can store a reference to another string in a String variable, once you have declared it,
by using an assignment. For example, we can change the value of our String variable myString to
the statement:
myString = "Strings can be knotty";
The effect of this is illustrated below:
The string itself is distinct from the variable you use to refer to it. In the same way as we saw with array
objects, the variable myString stores a reference to a String object, in other words, it keeps track of where
the string object is in memory. When we declare and initialize myString , it links to the initializing string
value. When we execute the assignment statement, the original link is severed, the old string is discarded, and
the variable myString stores a reference to the new string value. This means that you cannot extend the
string that is referred to in a variable of type String . String objects are said to be immutable - which just
means that they cannot be changed. To 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 we will 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 occupies
two bytes. 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, if you declare a variable of type String in a method without initializing it:
String anyString; // Uninitialized String variable
then it does not refer to anything.. If you don't want it to refer to anything at the outset, for instance, if you
may or may not assign a String object to it before you use the variable, then you must initialize it to a
special null value:
Search WWH ::




Custom Search