• 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
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Question from Javacaps mock

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class TestBuffer {
public void myBuf( StringBuffer s, StringBuffer s1) {
s.append(" how are you") ;
s = s1;
}
public static void main ( String args[] ) {
TestBuffer tb = new TestBuffer();
StringBuffer s = new StringBuffer("Hello");
StringBuffer s1 = new StringBuffer("doing");
tb.myBuf(s, s1);
System.out.print(s);
}
}
The answer is "Hello how are you". My question is that since the references of s and s1 have been passed to the method myBuff, why wouldn't s refer to where s1 is refering after the statement s=s1?
Thanks.
 
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, we cannot change the value contained in a StringBuffer by assigned with another variable using "=". Your StringBufer s will be referring to the variable s1. U will see in the following modified code... I reversed the value object s1, which is referred by s. The result is "gniod". I mean that s is referring to s1, not s'value is changed... Hope it is clear...


public class TestBuffer {
public void myBuf( StringBuffer s, StringBuffer s1) {
s.append(" how are you") ;
s = s1;
s.reverse();
}
public static void main ( String args[] ) {
TestBuffer tb = new TestBuffer();
StringBuffer s = new StringBuffer("Hello");
StringBuffer s1 = new StringBuffer("doing");
tb.myBuf(s, s1);
System.out.print(s1);
}
}

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic