• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

StringBuffer

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I RELEASE YOU! (for now .... ) Feel free to peruse this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic