Wednesday 6 March 2019

Java: Why does this swap method not work?




I have the following code:




public class Main {

static void swap (Integer x, Integer y) {
Integer t = x;
x = y;
y = t;
}

public static void main(String[] args) {

Integer a = 1;
Integer b = 2;
swap(a, b);
System.out.println("a=" + a + " b=" + b);
}
}


I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?


Answer




This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )



To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)



    Thing tmp = a;
a = b;
b = tmp;

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...