Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in String Buffer 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 "Doubt in String Buffer" Watch "Doubt in String Buffer" New topic
Author

Doubt in String Buffer

Bala Raj
Ranch Hand

Joined: Sep 12, 2000
Posts: 75
class StringBufferTest
{
public static void main(String args[])
{
StringBuffer sb1 = new StringBuffer("Sun");
StringBuffer sb2 = new StringBuffer("Exam");
aMethod(sb1, sb2);

System.out.println("sb1=" + sb1 + "; sb2=" + sb2);
}
static void aMethod(StringBuffer s1, StringBuffer s2)
{
s1.append(" Java");
s1=s2;
System.out.println("s1= " + s1 + "; s2= " + s2);
}
}
When I tried to execute the program: it is giving
s1= Exam; s2= Exam
sb1=Sunxxx; sb2=Exam
But I expected
s1= Exam; s2= Exam
sb1=Exam; sb2=Exam
Since we are assigning s1=s2. Can any one explain how?
(Probably it is very simple question... would have been discussed lot of times on this topic.)
Thanks in advance,
Bala
Bala Raj
Ranch Hand

Joined: Sep 12, 2000
Posts: 75
Sorry by mistake I put Sunxxx, it should be Sun Java
Bala
ricky gonzalez
Ranch Hand

Joined: Jun 30, 2000
Posts: 167
Hi, if you look closely, you will see that s1 is assigned to s2. Which means that before System.out.println(//...);, s1 == "Exam".
Thanks.
mohit joshi
Ranch Hand

Joined: Sep 23, 2000
Posts: 243

When you pass a reference to a function, a copy of the reference is passed. So if you change the object using this copy of reference, the object itself is changed. But if you overwrite the reference itself, then you loose the copy of reference, but the reference in the calling method still exists and points to the original object.
I hope i am clear enough.
Indian Joe
Greenhorn

Joined: Oct 04, 2000
Posts: 2
everythin in java is passed by value.
The situation u have depicted is as shown below
sb1----->"Sun"
sb2------>"exam"
now aMethod is invoked with the parameters s1 and s2.. the scenario is as follows
sb1----->"Sun"<------s1 <br /> sb2------>"exam"<------s2<br /> when s1.append(" Java"); is executed <br /> the scenario is<br /> sb1----->"Sun Java"<------s1 <br /> sb2------>"exam"<------s2<br /> when s1=s2; is executed the scenarion is as follows<br /> <br /> sb1----->"Sun Java"
sb2------>"exam"<------s2,s1

I hope this xplains.
 
 
subject: Doubt in String Buffer
 
Similar Threads
Difference of equals method in string and stringbuffer
StringBuffer
String & String Buffer
StringBuffer
arguments to method