Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swap function in java

 
viral patel
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone show me how to write Swap funtion in java. I tried but its not working properly.COde will be help lot.
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're from a C++ background, you may be envisioning something like this:

Alas, you cannot have a method with precisely those semantics in Java.
You'll have to use a temporary variable to swap two variables.
If you'd like to swap two items in an array, you can just do what comes naturally:
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to do it without a temporary holder check out this thread.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34410
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to elaborate on what David said:
You can't use a swap function with the semantics swap(int a, int b) because ints are passed by value, not by reference. If you want to swap the values of two objects, you can usually do that. You can also use the array as David explained.
If you are just using integers, it's less complicated to just do it in the code instead of in a separate function.
 
F A H A D
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
here goes buddy...

 
Spike Spiegel
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've been thinking about how to swap boolean values without using helper variables but I think it is impossible to do it in a clever way. The only way I could come up with is this:

Regards,
Hans
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic