Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from Javacaps mock

 
geeta rai
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • 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.
 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
  • 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);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic