Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arguments and Returns

 
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
 
fred rosenberger
lowercase baba
Bartender
Posts: 12147
31
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in your method func, you have 3 references to objects. when you say

b.append(", World.");

you are saying "take the object that b points to, and change it to something else.

then, when you say

w=a;
a=b;
b=w;

you are saying

"make w point to what a points to"(and the actual objects remains unchanged)
"make a point to what b points to"(and the actual objects remains unchanged)
"make b point to what w points to"(and the actual objects remains unchanged)

you then leave the method, and all three of those references are dropped from scope, and gone.

your original references, s1 and s2, still point to the same things they've always pointed to. s2's object was changed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic