aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes arguments to method 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 "arguments to method" Watch "arguments to method" New topic
Author

arguments to method

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
public class abc{
public void method1(StringBuffer s1, StringBuffer s2){
s1.append("there");
s2 = s1;
}
public static void main(String args[]){
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("Hello");
abc a = new abc();
a.method1(sb1,sb2);
System.out.println(" sb1 is " + sb1 + "and sb2 is " + sb2);
}
}

// The output of this is sb1 is Hellothere and sb2 is Hello.

can anybody explain me how this output has come.
Deepak M
Ranch Hand

Joined: Jul 10, 2000
Posts: 124
Here, s1 and s2 are passed by 'value'.
append method adds the string "there" to existing string "Hello" coz s1 is mutable.
public void method1(StringBuffer s1, StringBuffer s2){
s1.append("there");
s2 = s1;
}
However, s2 in method1 which is a copy of the reference s2 in main, simply points to s1 (bcoz of s2 = s1). Therefore s2 in main still contains "Hello"
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: arguments to method