This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes pass by reference- Swapping problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "pass by reference- Swapping problem" Watch "pass by reference- Swapping problem" New topic
Author

pass by reference- Swapping problem

Anil Deshpande
Ranch Hand

Joined: Jan 13, 2008
Posts: 119
This the program i have written to Swap the person Object. I know why it is not working. Because java always does pass by value.
Even for objects. But I really want to swap it. What can be done in the swap method?

The program is as follows.



and the out put is as follows

Anil
Ajay
Inside the swap method
Ajay
Anil
After Swapping
Anil
Ajay


Anil Deshpande
SCJP 1.5, SCWCD 1.5
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4180
    
  21

Anil Deshpande wrote:This the program i have written to Swap the person Object. I know why it is not working. Because java always does pass by value.
Even for objects. But I really want to swap it. What can be done in the swap method?


The method can't be made to swap them. So what do you need the swap method for? Sorting? Or just for show/proof of concept?


Steve
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19672
    
  18

You can use a two element array, and swap the array elements.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38428
    
  23
The rules about pass-by-reference in Java are easy to remember . . .

There is no such thing as pass-by-reference. Look at this FAQ.
Anil Deshpande
Ranch Hand

Joined: Jan 13, 2008
Posts: 119
Got It. Story is very good. Thanks a lot
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38428
    
  23
You're welcome
santhosh.R gowda
Ranch Hand

Joined: Apr 06, 2009
Posts: 296
Way too many people say "Java passes primitive by value and objects by reference". This is not the way it should be stated. Java passes everything by value. With primitives, you get a copy of the contents. With references you get a copy of the contents.


Creativity is nothing but Breaking Rules
 
 
subject: pass by reference- Swapping problem