Dan
Dan

Reputation: 463

Understanding swap function in java with a program

As I have read online that Java is pass by value and a general swap function won't swap the two values. I also read that it's not possible to swap the values of primitive types. I am wondering why the following program works and displays different valies after swap ?

public class swapMe {

    public static void main(String[] args) {
        int x = 10 , y = 20;

        System.out.println("Before");
        System.out.println("First number = " + x);
        System.out.println("Second number = " + y);

        int temp = x;
        x = y;
        y = temp;

        System.out.println("After");
        System.out.println("First number = " + x);
        System.out.println("Second number = " + y);
    }
}

Is it like somewhere, the original values of x = 10 and y = 20 are still stored somewhere and the swapped values displayed are not correct? Please advise. Thanks

Upvotes: 0

Views: 295

Answers (1)

Makoto
Makoto

Reputation: 106400

Not entirely sure where you're getting that information, but let's take this one at a time.

As I have read online that Java is pass by value and a general swap function won't swap the two values.

Correct...if the expectation of the swap is to happen by virtue of calling a method.

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

 // meanwhile, in main
 int x = 10;
 int y = 20;
 swap(x, y);
 System.out.println(x); // still prints 10
 System.out.println(y); // still prints 20

Incorrect...if the swap happens inside the method and is utilized somehow.

 public void swap(int x, int y) {
     int tmp = x;
     x = y;
     y = tmp;
     System.out.println(x);  // will print 20 from main
     System.out.println(y);  // will print 10 from main
 }

 // meanwhile, in main
 int x = 10;
 int y = 20;
 swap(x, y);
 System.out.println(x); // still prints 10
 System.out.println(y); // still prints 20

I also read that it's not possible to swap the values of primitive types.

No, this is perfectly possible to do. You can always reassign variables.

As to why your example above works, it's because you're holding onto one of the values while you reassign one of its variables. You're basically putting one value to the side while you copy it over.

Slowly...

int x = 10;
int y = 20;
int tmp = x; // tmp = 10
x = y;  // x = 20, tmp = 10
y = tmp;  x = 20, y = 10; tmp = 10 (but that doesn't matter)

Upvotes: 3

Related Questions