3

I'm trying to make a swap function in java but why is this not working?

void swap(int a, int b) {
   int temp = a;
   a = b;
   b = temp;
}
rjgodia
  • 68
  • 1
  • 5

3 Answers3

8

Because java is pass by value and not pass by reference. Your swap method will not change the actual a and b.You have actually swapped the a and b which have life only inside the method. You can check that by just printing the a and b inside the swap method.

You can return the values swapped with the help of array. (which was added first by sᴜʀᴇsʜ ᴀᴛᴛᴀ)

public class Test {

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

    public static void main(String[] args) {
        int a = 10,b = 5;
        int[] ba = swap(a,b);
        a = ba[0];
        b = ba[1];
        System.out.println(a);
        System.out.println(b);
    }

}
Community
  • 1
  • 1
akash
  • 22,664
  • 11
  • 59
  • 87
  • 1
    While I'm writing, you posted a good answer. Added my solution your answer. Feel free to review and revert :) – Suresh Atta Sep 27 '15 at 05:32
  • It may be worth noting that java is pass-by-value, however with objects in many ways it acts as if it is pass-by-reference since objects are really object pointers. – CollinD Sep 27 '15 at 06:38
2

Your swap just gets copies of values into a and b so you're only swapping the values in the a and b variables within the scope of swap.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Pantss
  • 63
  • 5
1
public class HelloWorld {
    private int a, b;
    HelloWorld(){
        this.a=0;
        this.b=0;
    }
    HelloWorld(int a, int b){
        this.a=a;
        this.b=b;
    }
    void swap() {
       int temp = this.a;
       this.a = this.b;
       this.b = temp;
    }
    public static void main(String[] args) {
        HelloWorld obj = new HelloWorld(10,5);
        obj.swap();
        System.out.println("a="+obj.a);
        System.out.println("b="+obj.b);
    }

}

If you are using local variable then scope would be within swap() method. But if you use it as instance variable this example would help.
The scope of instance variable would be available in whole class.
For scope you can check out
http://www.tutorialspoint.com/java/java_variable_types.htm
And if you want to use local variable then answer given by TAsk would be more helpful. Depending on your requirement.