Question

This question already has an answer here:

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

Was it helpful?

Solution

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

OTHER TIPS

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:

  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 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 :-)

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.

One-liner for any primitive numbers:

a += (b - (b = a));

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);

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

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

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.

This function will swap two ints

Integer[] swap(int a, int b){
    return new Integer[]{b,a};
}

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

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

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

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

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);
    }    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top