Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference Assignment Question

 
Rod Nichols
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you take the following code :
class TestClass {
public static void main( String[] args ) {
String s1 = new String( "Welcome to Java" );
String s2 = s1;
s1 += " and Welcome to HTML";
if( s1 == s2 ) {
System.out.println( "s1 is equal to s2" );
}
else {
System.out.println( "s1 is NOT equal to s2" );
}
}
}
and run it, the program will print :
s1 is NOT equal to s2
My question is, since s1 and s2 are both references to String objects, and pointing to the same String object, why are they not still equal after the string is appended ?
Rod
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rod,
Strings are immutable. What that means is that once a string object is created in memory it will never be changed. After the declarations are done in your example we have:
"Welcome to Java" <-- s1 <-- s2
Now we use the overloaded addtion operator and we have:
"Welcome to Java" <-- s2
"Welcome to Java and Welcome to HTML" <-- s1
We can see from above that we have 2 separate memory objects. Therefore when we perform your check we can easily see that they are not pointing to the same object!
Regards,
Manfred.
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rod
The behind the scenes look is that any time you appear change a String object, because Strings are immutable, what your actually doing is creating a new String. So when, in you example, you say s1 += " and Welcome to HTML";
What you're actually doing is creating a new String and having s1 refer to it. s2 still references the original String.
This is the same as what Manfred said just a different view.

Dave
[This message has been edited by Dave Vick (edited June 21, 2001).]
 
Rod Nichols
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave and Manfred,
Thank you for the explanations, that does clear it up a lot !!
Rod Nichols
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the interest of a full cross-reference
http://www.javaranch.com/ubb/Forum33/HTML/002616.html
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the whole 'immutable String' thing, I usually explain it as:
String concatenation is a shorthand thing that Java allows.
String two += "value";
is actually equivalent to:
String two = new String(two + "value");
therefore a new object is being created...
Dave.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic