-1

Why in this code i can't swap StringBuffer's?

 public static void main(String[] args) {
     StringBuffer a = new StringBuffer("One");
     StringBuffer b = new StringBuffer("Two");
     swap(a, b);
     System.out.println("a is " + a + "\nb is " + b);
 }

static void swap(StringBuffer a, StringBuffer b) {
    a.append(" more");
    b = a;
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
Vlad
  • 256
  • 3
  • 14
  • @HotLicks no insults or bashing, please... – Ordous Jul 24 '14 at 20:10
  • You could, of course, make your `swap` method "work", by having it swap *the contents* of the two objects. – Hot Licks Jul 24 '14 at 20:11
  • @Ordous - I apologize. He clearly understands how Java works, has thoroughly researched whether Java is call by reference or call by value, and is just jerking our chains. – Hot Licks Jul 24 '14 at 20:12
  • 1
    Have a look at this answer: http://stackoverflow.com/a/40523/3579095 – Lars Jul 24 '14 at 20:15
  • @HotLicks The question is clearly low quality and been discussed multiple times over. I imagine it will be closed or marked as duplicate within seconds. The user will also get his share of downvotes for both asking a silly no-effort question and the *way* he asked it. It's right to show him that (and possibly remove the ability to ask questions if this persists). But being offensive does not help at all. – Ordous Jul 24 '14 at 20:16
  • @Ordous - You apparently have never seen me be offensive. – Hot Licks Jul 24 '14 at 20:19

3 Answers3

0

Because you are not working with the reference of the variables a and b but with new StringBuffer("One") and new StringBuffer("Two") references.

So with b = a you don't change a and b in main but local copies.

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53
0

Java doesn't support pass by reference, only pass by value. StringBuffer a is a reference, and this reference is passed by value.

Please don't use StringBuffer as it was replaced by StringBuilder ten years ago.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0
static void swap(StringBuffer a, StringBuffer b) {
       a.append(" more");
       b = a; // the change is local to swap(). It doesn't affect main()
}
Shlublu
  • 10,917
  • 4
  • 51
  • 70