Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my java swap function not working? [duplicate]

Tags:

java

swap

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;
}
like image 536
rjgodia Avatar asked Jul 10 '26 21:07

rjgodia


1 Answers

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

}
like image 195
akash Avatar answered Jul 13 '26 13:07

akash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!