File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pass by reference- Swapping problem

 
Anil Deshpande
Ranch Hand
Posts: 119
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Rob Spoor
Sheriff
Pie
Posts: 20369
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use a two element array, and swap the array elements.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 119
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got It. Story is very good. Thanks a lot
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
santhosh.R gowda
Ranch Hand
Posts: 296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic