Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String question

 
Erin Goettl
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found this example on a site for SCJP notes and I wanted to clarify. Here is the code:

void changeObjects(String str, StringBuffer sb)
{
str = "123"; //makes the reference str to point to new string object containing "123". you are changing the reference here.
str = str + "123"; //strings are immutable. It will create a new string containing "abc123". The original "abc" will remain as it is.
sb.append("123"); //changes the actual object itself. you are NOT changing the reference here.
}

....
String s = "abc";
StringBuffer sb = new StringBuffer("abc");
changeString(s, sb);
System.out.println(s); //Will still print "abc".
System.out.println(sb); //Will still print "abc123".

My question was regarding the second line in the changeObjects function. Because str's value is set to "123", after the second line wouldn't str's value now be "123123" and NOT "abc123" as stated here? I understand why when there is a System.out.println(s) later on that "abc" is printed out but I don't understand why "123123" wouldn't be the value for str after the second line in the function.

Thanks!
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes the second line will print 123123. Check this out...
Modified your code...



Hope this helps you.

[ December 07, 2004: Message edited by: Jay Pawar ]
[ December 07, 2004: Message edited by: Jay Pawar ]
 
Anand Ko
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That answers part of his question.

The function will just point the String reference to different string ("123") and hence the actual string value passed won't be changed after the function return call.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic