Java Reference
In-Depth Information
allocate memory space of a specific type. However, in the case of reference variables of type
String , we can also use the assignment operator to allocate memory space to store a string
and assign the string to a String variable. Consider the following statements:
String str;
//Line 1
The statement:
str = "Hello"; //Line 2
creates a String object with the value "Hello" , if one does not exist, and stores the
reference of that object in str (see Figure 7-7).
1500
str
1500
Hello
FIGURE 7-7 Variable str and the string object
7
We assume that the address of the memory space where the string "Hello" is stored is
1500 . Now suppose that you execute either the statement:
str = "Hello There";
or the statement:
str = str + " There";
The effect of either of these statements is illustrated by Figure 7-8.
1800
str
1800
Hello There
FIGURE 7-8 str after the statement str ¼ "Hello There" ;or str ¼ str + " There" ;
executes
Note that the string "Hello There" is stored at a different location. It is now clear that
any time you assign a different string to a String variable, the String variable points to
a different object. In other words, when a string is created and assigned to a String
variable, the string cannot be changed. Note that the class String does not contain any
method that allows you to change an existing string.
If you pass a String variable, that is, a reference variable of the String type, as a
parameter to a method, and within the method you use the assignment operator to
 
Search WWH ::




Custom Search