Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to swap two variables in Java? [duplicate]

Tags:

java

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?

like image 919
Dibyendu Avatar asked May 01 '12 04:05

Dibyendu


People also ask

How do you swap two variables in Java?

Two variables can be swapped in one line in Java. This is done by using the given statement. x = x ^ y ^ (y = x); where x and y are the 2 variables.

Can we swap 2 variables without a third one?

Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.

Can we swap two objects in Java?

The Java Collections Framework's classes have a built-in method to swap elements called swap(). The java. util is a utility class that contains static methods that can operate on elements like Lists from the Collection interface. Using the swap method is much easier than the example we discussed earlier.


1 Answers

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.

like image 159
cHao Avatar answered Sep 19 '22 17:09

cHao