aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with StringBuffer and call by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with StringBuffer and call by reference" Watch "Problem with StringBuffer and call by reference" New topic
Author

Problem with StringBuffer and call by reference

Sandeep Ghosh
Ranch Hand

Joined: Jan 23, 2002
Posts: 145
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

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
wood burning stoves
 
subject: Problem with StringBuffer and call by reference