Is it possible to write swap method in Java?
JavaSwapPrimitive TypesJava Problem Overview
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?!
Java Solutions
Solution 1 - Java
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
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)
). Use this to impress your friends and confuse your enemies :-)
Solution 2 - Java
Without using an array or objects, no, it is not possible to do it within a method.
Solution 3 - Java
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.
Solution 4 - Java
One-liner for any primitive numbers:
a += (b - (b = a));
Solution 5 - Java
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);
Solution 6 - Java
>In java5, the closest I can think of, which may help you, is :
The AtomicInteger class (and others) have getAndSet()
atomic methods ..
Solution 7 - Java
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.
Solution 8 - Java
This function will swap two ints
Integer[] swap(int a, int b){
return new Integer[]{b,a};
}
Solution 9 - Java
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
Solution 10 - Java
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
Solution 11 - Java
As Thomas Owens said. You could probably do it in C by passing variables by &reference, but afaik not in Java without using objects.
Solution 12 - Java
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
Solution 13 - Java
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);
}
}