• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in String Buffer

 
Bala Raj
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry by mistake I put Sunxxx, it should be Sun Java
Bala
 
ricky gonzalez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic