30

Possible Duplicate:
Is it possible to write swap method in Java?

Given two values x and y, I want to pass them into another function, swap their value and view the result. Is this possible in Java?

Community
  • 1
  • 1
noNameYet
  • 635
  • 2
  • 10
  • 15
  • 8
    *Is this possible in Java?* and the answer is : ***YES*** – Harry Joy May 01 '12 at 04:56
  • 1
    "Swap their value"? Do you mean _variables_ x and y? And you want the two variables to have each other's value after the call? – Ray Toal May 01 '12 at 04:57
  • Have you checked this [Program to Swap two variables or number](http://www.msccomputerscience.com/2013/01/swapping-using-temporary-or-third.html">Write). – ARJUN Nov 06 '14 at 12:01
  • you can come close, as can be seen in at least 2 answers from http://stackoverflow.com/questions/3624525/how-to-write-a-basic-swap-function-in-java – Chris Apr 02 '17 at 10:38
  • See https://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java – Raedwald Nov 20 '18 at 21:23

2 Answers2

38

Not with primitive types (int, long, char, etc). Java passes stuff by value, which means the variable your function gets passed is a copy of the original, and any changes you make to the copy won't affect the original.

void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
    // a and b are copies of the original values.
    // The changes we made here won't be visible to the caller.
}

Now, objects are a bit different, in that the "value" of an object variable is actually a reference to an object -- and copying the reference makes it point at the exact same object.

class IntHolder { public int value = 0; }

void swap(IntHolder a, IntHolder b)
{
    // Although a and b are copies, they are copies *of a reference*.
    // That means they point at the same object as in the caller,
    // and changes made to the object will be visible in both places.
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

Limitation being, you still can't modify the values of a or b themselves (that is, you can't point them at different objects) in any way that the caller can see. But you can swap the contents of the objects they refer to.

BTW, the above is rather hideous from an OOP perspective. It's just an example. Don't do it.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • May I ask why it is hideous from an OOP perspective? I've seen object mutation in child methods all the time. I would add null checks on both `a` and `b` though. – ADTC Nov 10 '12 at 08:45
  • 1
    @ADTC: (1) This isn't a child method; it's the *whole other function* the OP was asking for. If the function were defined in `IntHolder`, and `value` were private, maybe...but (2) what's worse is, either way, a `swap` like this is only really useful when you demote objects to "value holders". When you do that, you forget the very reason behind OOP; data becomes just some stuff that functions operate on, which is a step *backwards* from an object-oriented perspective. – cHao Nov 10 '12 at 13:10
  • Even if we could look or work past both of those facts, (3) the addition of a `swap` method to `IntHolder` would nearly necessitate that we remove inheritance as well as encapsulation. (Otherwise, every subclass would also have to have a method that called `super.swap(b);` and then swapped its own fields, *just to avoid breaking `swap(b)`*. That gets pretty ugly, pretty fast, and can't be enforced by the Java compiler.) So now, we've tossed out encapsulation *and* inheritance, and pretty much abandoned any attempt at polymorphism as well. That's *all three* of the main OOP concepts. – cHao Nov 10 '12 at 13:27
  • @cHao Wow, thanks! It's clear now why it's hideous. It really is hideous. – ADTC Nov 10 '12 at 17:18
5

I'm going to be reallllyyyy annoying and pedantic here because the word "value" has a very specific meaning in Java, which people often don't often understand, especially when the variables hold references to objects.

I am going to assume the question asks for this behavior:

x = initialValueForX;
y = initialValueForY;
swap(x, y);
// x now holds initialValueForY;
// y now holds initialValueForX;

This is not possible because Java passes all arguments to methods by value. You can never change the actual value stored inside of x and y this way.

You can, however, if x and y hold references to objects, change the properties of the two objects in such a way as to make the printed values look like each other's initial values:

x = initialValueForX;
y = initialValueForY;
swap(x, y);
System.out.println(x);  prints what looks like initialValueForY
System.out.println(y);  prints what looks like initialValueForX

This works if your understanding of value is what the object looks like, rather than what the identity of an object is. Usually, that is acceptable.

(Was going to give a good example here, but cHao already did. Plus others pointed out that this was a duplicate question anyway.)

Ray Toal
  • 86,166
  • 18
  • 182
  • 232