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?!
- 91,294
- 38
- 174
- 232
-
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;
}
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
bis evaluated in order to be passed as the first argument to the function - The expression
b = ais 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
band 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)). Use this to impress your friends and confuse your enemies :-)
- 4,721
- 3
- 26
- 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
Without using an array or objects, no, it is not possible to do it within a method.
- 111,344
- 96
- 305
- 429
-
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.
- 18,046
- 6
- 48
- 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);
- 10,936
- 5
- 55
- 50
-
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 ..
- 22,953
- 4
- 54
- 60
-
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,378
- 18
- 70
- 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
- 1
- 1
-
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);
}
}
- 126,953
- 40
- 282
- 279
- 21