Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

arguments to method

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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"
 
grapes are vegan food pellets. Eat this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic