File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Swap function in java

viral patel

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
author & internet detective

Joined: May 26, 2003
Posts: 33122

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2

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

no GOD except ALLAH...
Spike Spiegel

Joined: Aug 20, 2003
Posts: 20
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:

I agree. Here's the link:
subject: Swap function in java
jQuery in Action, 3rd edition