Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Arguments and Returns  RSS feed

 
mi te
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a code, which I have no idea what is going on.

class F{
static void func(StringBuffer a, StringBuffer b){
b.append(", World.");
StringBuffer w = a;
a = b;
b = w;
}
}
class ArgsReturn{
public static void main(String args[]){
StringBuffer s1 = new StringBuffer("Hello");
StringBuffer s2 = new StringBuffer("Hello");
F.func(s1, s2);
System.out.println(s1);
System.out.println(s2);
}
}

//output
Hello
Hello, World

I guess that b.append(", World") changes the value of s2, but then why don't a = b; or b = w; do the same thing? They are still assigning StringBuffer objects to StringBuffer objects, aren`t they? Please someone clear this up for me so I can sleep in peace.
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is nothing to do with Servlets, and should be in Java in General (intermediate)

To answer your query:
the changes a = b; or b = w; works just local to static void func() method. But the changes b.append(", World."); are applied on actual reference and you are able to see this change from the place where you called func method.

For more details read the following article: Why can't you swap in Java?
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java in General (beginner)

Dave
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!