File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Arguments and Returns Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arguments and Returns" Watch "Arguments and Returns" New topic

Arguments and Returns

mi te

Joined: Mar 09, 2006
Posts: 29
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);

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

Joined: Sep 20, 2003
Posts: 1704
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

Joined: Mar 06, 2001
Posts: 13459

Moving to Java in General (beginner)

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

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


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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Arguments and Returns
It's not a secret anymore!