Java Reference
In-Depth Information
Strings, the Assignment Operator, and the Operator new
Suppose that str is a String variable and we want to assign the string "Sunny" to str .
As explained in Chapter 3, this can be accomplished by using the statement:
str = "Sunny";
//Line 1
or the statement:
str = new String("Sunny"); //Line 2
After the execution of the statement in Line 1 or Line 2, str will point to the String
object with the value "Sunny" . Recall from Chapter 3 that the statement in Line 2
explicitly uses the operator new .Alsorecallthatthereisaslightdifferenceintheway
these statements execute. When the statement in Line 1 executes, the computer checks
whether there already is a String object with the value "Sunny" ; if so, then the address
of that object is stored in str . On the other hand, when the statement in Line 2
executes, the computer will create a new String object with the value "Sunny"
regardless of whether such a String object already exits. Let us further explain this
concept.
Consider the following statements:
String str1 = "Hello";
String str2 = "Hello";
4
When the first statement executes, a String object with the value "Hello" is created
and its address is assigned to str1 . When the second statement executes, because there
already exists a String object with the value "Hello" , the address of this String object
is stored in str2 (see Figure 4-7).
str1
Hello
str2
FIGURE 4-7 Variables str1 , str2 , and the objects to which they point
Therefore, if you evaluate the expression (str1 == str2) after these statements, this
expression evaluates to true . Moreover, here the expression str1.equals(str2) also
evaluates to true .
If you later assigned a different string, say, "Cloudy" ,to str2 ,thenifno String
object exists with the value "Cloudy" ,a String object with this value is created and
its address is stored in str2 . However, str1 would still point to the string "Hello" .
In other words, changing the value of the string str2 does not change the value of
the string str1 .
 
Search WWH ::




Custom Search