• 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:

String Buffer

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1 public class StrBufTest {
2 public void method1(StringBuffer s1, StringBuffer s2){
3 s1.append("There");
4 s2 = s1;
5 }
public static void main(String[] args){
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("Hello");
StrBufTest sbt = new StrBufTest();
sbt.method1(sb1, sb2);
System.out.println("sb1 is " + sb1 + "\nsb2 is " + sb2);
}
}
Answer is: sb1 is "HelloThere"; sb2 is "Hello".
When we say s2 = s1. It creates copy of reference. both should have save content. How come sb1 and sb2 is different???
 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1 public class StrBufTest {
2 public void method1(StringBuffer s1, StringBuffer s2){
3 s1.append("There"); //
here u are manipulating on the string directly
and so u see the change
4 s2 = s1;// u are changing the ref of the local s2 object
in method argument
5 }
public static void main(String[] args){
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("Hello");
StrBufTest sbt = new StrBufTest();
sbt.method1(sb1, sb2);
System.out.println("sb1 is " + sb1 + "\nsb2 is " + sb2);
}
}
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can somebody throw more light, i dont get it
 
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please refer to this dicussion and let us know if you are convinced.
regds
maha anna
 
She said she got a brazillian. I think owning people is wrong. That is how I learned ... tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic