File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Reference Assignment Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reference Assignment Question" Watch "Reference Assignment Question" New topic

Reference Assignment Question

Rod Nichols

Joined: Apr 19, 2001
Posts: 23
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 ?
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
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!
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
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.

[This message has been edited by Dave Vick (edited June 21, 2001).]

Rod Nichols

Joined: Apr 19, 2001
Posts: 23
Dave and Manfred,
Thank you for the explanations, that does clear it up a lot !!
Rod Nichols
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

In the interest of a full cross-reference
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

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...
I agree. Here's the link:
subject: Reference Assignment Question
It's not a secret anymore!