| Author |
pass by reference- Swapping problem
|
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
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: 3026
|
|
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: 19216
|
|
|
You can use a two element array, and swap the array elements.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
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: 117
|
|
|
Got It. Story is very good. Thanks a lot
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
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
|
|
|