views:

1321

answers:

6

Here is the question: write a method that swaps two variables. These two variables should be primitives. It doesn't need to be generic e.g. two int variables. Is there a way?!

+7  A: 

Without using an array or objects, no, it is not possible to do it within a method.

Thomas Owens
Thanks. It puzzled me for a while. I thought there should be a way! :)
AraK
btw, arrays are objects, so you really only needed to say objects. from java.sun.com: "An array is a container object that holds a fixed number of values of a single type." being picky i know :)
geowa4
+5  A: 

Check out this JavaWorld article that explains it in detail:

http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

A swap of two primitives will never work because primitives are passed by value in Java. You can't even write a method to swap two objects for that matter.

Like @Thomas said, the only thing you could do is have your primitives contained within other objects/arrays and modify those.

Brent Nash
+1  A: 

In java5, the closest I can think of, which may help you, is :

The AtomicInteger class (and others) have getAndSet() atomic methods ..

KLE
The question is specifically about primitive types. These are objects.
Thomas Owens
@Thomas: "**should** be primitives"
geowa4
@Thomas OK. I don't have a clue then. @geowa4 Thanks for your support :-)
KLE
A: 

As Thomas Owens said. You could probably do it in C by passing variables by &reference, but afaik not in Java without using objects.

Chris Holland
+1  A: 

To write a swap method that swaps primitives you'd have to have the concept of "out" variables, i.e. variables whose values are passed up to the calling context. C# has those but you must still specify that they're out variables.

Michael Wiles
A: 

You can write method which will return two-elements array which contents are swapped parameters to that method.

static Object[] swap(Object a, Object b) {
    return new Object[]{b,a};
}
Victor Sorokin