jquery404 jquery404 - 1 year ago 69
Java Question

How to swap two any type of variables without using a temp variable?

I want to swap two variables. They can be string, int or double.
How can I do that without using a temporary variable?

Answer Source

You can swap numeric primitive types (int, double, float, ...) without a temporary variable:

a = a + b;
b = a - b;
a = a - b;

For strings (by using a temporary variable for the length):

int len1 = s1.length();
s1 = s1 + s2;
s2 = s1.substring(0, len1);
s1 = s1.substring(len1);

But you can't swap object references without a temporary variable. But a temporary doesn't hurt, so why don't you want to use it?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download