Take the 2-minute tour ×

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?!

share|improve this question
Safety first! :) –  crunchdog Sep 1 '09 at 15:53
@crunchdog Sometime I shall understand Java! –  AraK Sep 1 '09 at 16:01
Chk this out.More info on swap by reference. cs.utsa.edu/~wagner/CS2213/swap/swap.html Chk this out.More info on swap by reference. –  user1487767 Jun 28 '12 at 7:27

12 Answers 12

up vote 31 down vote accepted

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

share|improve this answer
Thanks. It puzzled me for a while. I thought there should be a way! :) –  AraK Sep 1 '09 at 15:59
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 Sep 1 '09 at 16:00
So how is it possible by using arrays or objects? Are these arrays or objects not used inside a method? Are they global? Or can one swap objects inside a method using local arrays or objects? –  c0d3Junk13 Mar 21 '12 at 19:50
@geowa4 I thinks it is okay to say both to introduce to new comer that array is an object. –  Ifan Iqbal Oct 23 '13 at 8:07

Check out this JavaWorld article that explains it in detail:


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.

share|improve this answer

While it is not possible to write a function that simply swaps two variables, it is possible to write a helper function that allows you to:

  • Swap two variables using only one statement
  • Without temporary variables in the caller's code
  • Without 'boxing' primitives
  • With a few overloads (one of them using generics), it works for any type

That's how you could do it:

int returnFirst(int x, int y) {
    return x;
int a = 8, b = 3;
a = returnFirst(b, b = a); // try reading this as a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8

This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:

  1. The original value of b is evaluated in order to be passed as the first argument to the function
  2. The expression b = a is evaluated, and the result (the new value of b) is passed as the second argument to the function
  3. The function executes, returning the original value of b and ignoring its new value
  4. You assing the result to a

If returnFirst is too long, you can choose a shorter name to make code more compact (e.g. a = _(b, b = a)). Use this to impress your friends and confuse your enemies :-)

share|improve this answer
If you name your function _, then you can almost write a=b;b=a;. See how clean(?) it looks: a=_(b,b=a); –  marcus May 30 '13 at 21:51
Ouch, _ is deprecated as an identifier in Java 8 and could be removed in Java 9. Not sure what they are going to use it for. –  marcus Oct 26 at 0:09

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

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

share|improve this answer
The question is specifically about primitive types. These are objects. –  Thomas Owens Sep 1 '09 at 15:49
@Thomas: "should be primitives" –  geowa4 Sep 1 '09 at 15:58
@Thomas OK. I don't have a clue then. @geowa4 Thanks for your support :-) –  KLE Sep 1 '09 at 16:17

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.

share|improve this answer

This function will swap two ints

Integer[] swap(int a, int b){
    return new Integer[]{b,a};
share|improve this answer

You can make a generic version of @marcus's swap method that swaps any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];

b = swap(a, a=b);
z = swap(x, x=y, y=z);
share|improve this answer
A vararg function will create a temporary array (Object[]) to pass all the objects. I'm not sure how the JIT will behave at runtime, but creating an array to swap two values looks a little wasteful, unless you really need a rotate function for an unspecified number of objects. –  marcus Feb 4 at 12:19
For a fixed number of values you can do it without the array. –  dansalmo Feb 4 at 16:07

Here's a method that swaps two primitive variables

private void swap(){
    int a = 1;
    int b = 2;
    int temp = a;
    a = b;
    b = temp;

It might not be of much use though ;)

Ok seriously, it could be done if the variables are class level:

public class MyClass{
    // excuse horrible coding practice of public mutable fields
    public int a = 1;
    public int b = 2;

    public void swap(){
        int temp = a;
        a = b;
        b = temp;

Again though, I fail to see what the use of this could be

share|improve this answer
This answered the question as written - why the downvote? –  wonderer Mar 4 at 17:05

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

share|improve this answer

I'm not to happy with the other answers: Actually you can use this to invert 2 dataTypes which allow the use of ^ operator.

y = (x ^= (y ^= x)) ^ y;

Ugly, but it works.

share|improve this answer

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};
share|improve this answer
public class Swap
    public static void main (String[]args)
        int y = 5;
        int x = 4;
        int c;

        System.out.println("y = "+y);
        System.out.println("x = "+x);

        c=x; //c = 4
        x=y; //x = 5;

        System.out.println("y= "+y);
        System.out.println("x= "+x);
share|improve this answer

Your Answer


