-1
public class freedom {

    public static void main(String args[]){
        int x = 10;
        int y = 20;
        System.out.println(" x is: "+x+" y is: "+y);
        swap(x,y);
        System.out.println(" x is: "+x+" y is: "+y);
    }

    public static void swap(int x, int y){
        int temp = x;
        x = y;
        y = temp;
    }
}

So i wrote a simple function to swap two values but for some reason they do not get swapped. I know the logic of my code is correct but I am wondering why the values are not swapped.

Dinero
  • 1,070
  • 2
  • 19
  • 44

1 Answers1

1

Your problem is that Java (when it comes to primitive values such as ints) is "pass-by-value", while your code inherently assumes "pass-by-reference". See https://www.javaworld.com/article/2077424/learn-java-does-java-pass-by-reference-or-pass-by-value.html as a great description of why this is. In short, when the function is called, the parameters are essentially "copied" into the function as new variables that are distinct from the original, although they have the same value. Thus, those variable's contents change independently of the parent function variables' contents.

Roguebantha
  • 814
  • 4
  • 19