aspose file tools*
The moose likes Java in General and the fly likes Swap function in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Swap function in java" Watch "Swap function in java" New topic
Author

Swap function in java

viral patel
Greenhorn

Joined: Feb 25, 2003
Posts: 16
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

Joined: Jul 27, 2001
Posts: 1365
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

Joined: Jan 30, 2002
Posts: 3451
If you want to do it without a temporary holder check out this thread.


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30512
    
150

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
F A H A D
Greenhorn

Joined: Aug 16, 2003
Posts: 13
hi,
here goes buddy...



no GOD except ALLAH...
Spike Spiegel
Greenhorn

Joined: Aug 20, 2003
Posts: 20
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Swap function in java