File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String question" Watch "String question" New topic
Author

String question

Erin Goettl
Ranch Hand

Joined: Dec 06, 2004
Posts: 35
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

Joined: Aug 27, 2004
Posts: 411
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 ]

Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
Anand Ko
Ranch Hand

Joined: Dec 03, 2003
Posts: 79
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.


Anand<br />SCJP 1.4, SCWCD 1.4, SCEA 5.0(1/3)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String question
 
Similar Threads
String Buffer
Passing String into a method causes the method to have it's own copy, correct?
Objects
some questions,please
Name the mutable and immutable Classes