File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in String Buffer" Watch "Doubt in String Buffer" New topic

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");
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 Raj
Ranch Hand

Joined: Sep 12, 2000
Posts: 75
Sorry by mistake I put Sunxxx, it should be Sun Java
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".
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

Joined: Oct 04, 2000
Posts: 2
everythin in java is passed by value.
The situation u have depicted is as shown below
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"

I hope this xplains.
I agree. Here's the link:
subject: Doubt in String Buffer
jQuery in Action, 3rd edition