This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

pass by reference- Swapping problem  RSS feed

 
Ranch Hand
Posts: 119
  • 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

 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • 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?
 
Sheriff
Posts: 21289
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use a two element array, and swap the array elements.
 
Marshal
Posts: 58421
178
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got It. Story is very good. Thanks a lot
 
Campbell Ritchie
Marshal
Posts: 58421
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Ranch Hand
Posts: 296
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!