jQuery in Action, 3rd edition
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String question" Watch "String question" New topic

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.

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)
I agree. Here's the link: http://aspose.com/file-tools
subject: String question
It's not a secret anymore!