Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

String Buffer

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
can somebody throw more light, i dont get it
 
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please refer to this dicussion and let us know if you are convinced.
regds
maha anna
reply
    Bookmark Topic Watch Topic
  • New Topic