Win a copy of Emmy in the Key of Code this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

String question

 
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!
 
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 ]
 
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.
 
Trust God, but always tether your camel... to this tiny ad.
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!