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;
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With