• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer

 
Santoo
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought the answer would be HELLOTHERE,HELLOTHERE but sb2 is still HELLOO.
can anyone explain this.

public class Test{
public void method1(StringBuffer s1,StringBuffer s2){
s1.append("THERE");
s2=s1;
}
public static void main(String arg[]){
StringBuffer sb1=new StringBuffer("HELLO");
StringBuffer sb2=new StringBuffer("HELLOO");
Test t=new Test();
t.method1(sb1,sb2);
System.out.println("sb1 is"+sb1+"sb2 is"+sb2);
}}
answer is HELLOTHERE,HELLOO
Thanks in advance.
 
Sandeep Potnis
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santoo,
This looks likes a "passing a reference by value" issue.
Try to re-think the question on those lines.
Sandeep
 
robl
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sandeep Potnis:
Santoo,
This looks likes a "passing a reference by value" issue.
Try to re-think the question on those lines.
Sandeep

I believe that is correct. When you pass an object as a parameter, you are passing a reference(actually a copy of the reference) and you can not effect the contents of the object without invoking a method. s2 = s1 simple changes the reference locally and does not effect the reference of the calling method.
I hope that makes sense. Maybe somebody else can explain it better.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic