• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with StringBuffer and call by reference

 
Sandeep Ghosh
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
please c the code below.I thought answer should be "one more" will be printed twice,but output is
one more
two
Why???
Sonu
public class Test {
public static void main(String args[]) {
StringBuffer a = new StringBuffer("One");
StringBuffer b = new StringBuffer("Two");
Test.swap(a,b);
System.out.println("a is "+ a +"\nb is " + b);
}
static void swap (StringBuffer a, StringBuffer b) {
a.append(" more");
b=a;//what is happening over here
}
}
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, everything is passed by value. A copy of a reference is passed to a method, so that you may interact and mutate the referenced object but not make the reference point to some other object.
So the statement b=a; in method swap has only a local effect, that is, b will point to a only in the method scope and the assignment does not affect the original StringBuffer outside of swap.
Read this: http://www.javaranch.com/campfire/StoryPassBy.jsp
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic