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

- 94,250
- 39
- 176
- 234
-
Chk this out.More info on swap by reference. http://www.cs.utsa.edu/~wagner/CS2213/swap/swap.html Chk this out.More info on swap by reference. – Jun 28 '12 at 07:27
13 Answers
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;
}
<T> T returnFirst(T x, T y) {
return x;
}
// other overloads as needed
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 15.12.4.2) 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:
- The original value of
b
is evaluated in order to be passed as the first argument to the function - The expression
b = a
is evaluated, and the result (the new value ofb
) is passed as the second argument to the function - The function executes, returning the original value of
b
and ignoring its new value - You assign the result to
a
If returnFirst
is too long, you can choose a shorter name to make code more compact (e.g. a = sw(b, b = a)
).
Suppose you need to swap many variables of different types one after the other. By using returnFirst there's no need for intAux, objAux, etc. There's less risk of mistakenly using the wrong variable somewhere, because there are no extra variables (in the caller, at least).

- 5,041
- 3
- 30
- 36
-
3If 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
-
2Ouch, _ 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 '14 at 00:09
-
-
1I think this should be an accepted answer! Awesome (but yes, totally impractical) – Osman-pasha Jan 15 '16 at 17:52
-
@marcus i think use of _ as an identifier is discouraged not disallowed since java 8 (compiler might show a warning) but Use of _ as indentifier with Lambdas will show a compile time error. – Alok Mishra Dec 28 '16 at 07:31
-
I have found out that they plan to officialize _ as the "unused" variable/parameter: http://www.coffee-bytes.com/2013/08/01/reclaiming-underscore/ http://www.tothenew.com/blog/why-you-should-stop-using-underscore-as-variable-name-in-java/ The path to that goal, however, seems painfully slow (version 8 and 9 disallowing it, maybe version 10 will add the new semantics) – marcus Dec 28 '16 at 19:03
-
Don't learn this pattern if you ever need to port your code to C++, or you plan to work with C++. This is unspecified behavior in C++. You probably will get a == b in C++ at the end. – 0kcats Mar 29 '23 at 18:00
-
Yeah, when I said "unlike some other languages" I was really thinking about C and C++ but I didn't think it was necessary to mention them explicitly. – marcus Mar 29 '23 at 23:12
Without using an array or objects, no, it is not possible to do it within a method.

- 114,398
- 98
- 311
- 431
-
2btw, 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 01 '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? – C0D3 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 08:07
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.

- 19,075
- 7
- 52
- 56
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);

- 11,506
- 5
- 58
- 53
-
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 04 '14 at 12:19
-
For a fixed number of values you can do it [without the array](http://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java/20600020#20600020). – dansalmo Feb 04 '14 at 16:07
In java5, the closest I can think of, which may help you, is :
The AtomicInteger class (and others) have getAndSet()
atomic methods ..

- 23,689
- 4
- 56
- 62
-
The question is specifically about primitive types. These are objects. – Thomas Owens Sep 01 '09 at 15:49
-
-
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.

- 20,902
- 18
- 71
- 101
This function will swap two ints
Integer[] swap(int a, int b){
return new Integer[]{b,a};
}

- 21
- 1
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

- 21
- 1
I have read the above answers seeking an explanation as to why it is said that a swapping program cannot be written in java in the way it is written in c++. I did the following way program screenshot

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

- 9
- 3
Yes it is possible to swap two variable using a method. But you should declare that method with empty parentheses and then call it by reference(empty parentheses) . Here is an example that illustrates swapping of two variable using a method.
public class Swapping
{
static String A="Apple";
static String B="Bat";
public static void swap()
{
String k;
k=A;
A=B;
B=k;
}
public static void main(String[] args)
{
System.out.println("Before swapping");
System.out.println("A= "+A);
System.out.println("B= "+B);
swap();
System.out.println("After swapping");
System.out.println("A= "+A);
System.out.println("B= "+B);
}
}
By compiling the above code the output comes as follows:
Before swapping
A= Apple
B= Bat
After swapping
A= Bat
B= Apple
//In case of call by reference original value is changed if we made changes in the called method

- 21
- 2
-
This is a method that swaps the values of two variables in a class, not two variables passed as parameters. And calling a method with no parameters is NOT calling a method by reference. – John Allen Feb 27 '18 at 08:06
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;
y=c;
System.out.println("\n");
System.out.println("y= "+y);
System.out.println("x= "+x);
}
}

- 129,200
- 40
- 280
- 281

- 21