Java Software Programming Examples For Beginners / Interview: How To Swap Integer (and String) Variables Without Using a Temporary Variable
By Angsuman Chakraborty, Gaea News NetworkSaturday, October 29, 2005
Say x & y are the integer variables. The challenge is to swap them without using a temporary variable.
The solution is as simple as the problem itself:
x = x + y;
y = x - y;
x = x - y;
Update 1: Jack and Alexey pointed out a typo in my solution which has since been corrected. Please see their comments below.
The simplicity of the solution appeals to me. It clearly demonstrates the meaning of assignment operator ( “=” ).
What if they are Strings?
Note: You can use String methods in Java API.
Here is the solution:
x = x + y;
y = x.substring(0, x.indexOf(y));
x = x.substring(x.indexOf(y) + y.length());
Can you see the similarity?
Can you provide a simpler solution to either of the above?
Update 2: Robert just did (see his comment below). He pointed out that the String solution doesn’t work when one string is contained in another. His solution is:
x = x + y;
y = x.substring(0, x.length() - y.length());
x = x.substring(y.length());
July 30, 2010: 9:52 am
Use Of try, Catch ,throw, throws & final plz give me the best website for this in Simple Language for Understanding this.. |
Sanket |
February 26, 2008: 4:34 am
if(x > y) |
Binu K James |
November 29, 2007: 8:30 am
import java.io.*; the question is .. Is it possible to run this program with out changing if(x=6) |
aki |
September 28, 2006: 6:10 am
im coding a anagram word game to swap letters from one label to another (up to the down) by using a threeBottons class how should i use the string and char code? (the second character of label one should place to the second character of label two) i need that much help thanks |
Fred |
November 9, 2005: 2:08 am
Unfortunately, the code to exchange integer values will fail for values that cause over- or underflow.
However, you can use exclusive-or (xor), which is like add without carry. The following unobvious code exchanges all int values.
|
October 31, 2005: 8:53 am
@Robert
|
Robert |
October 31, 2005: 8:15 am
The string sample will fail if the string x contains the string y. For example, String x = “Hello World”; Step 1: x = x + y; x = “Hello WorldHello” Step 2: y = x.substring(0, x.indexOf(y)); x.indexOf(y) = 0, so y = “”; Step 3: x = x.substring(x.indexOf(y) + y.length()); x.indexOf(y) = 0 and y.length = 0, so x = “Hello WorldHello” You can fix this by using lastIndexOf() method in String like x = x + y; or you could eliminate the indexOf() calculations altogether and just use the lengths of the strings x = x + y; |
October 30, 2005: 9:24 am
@Jack & Alexey Just checking if you are attentive |
Alexey |
jack |
jack |
October 30, 2005: 2:53 am
x : 1 y : 2 x = x + y; x = x - y; y = x - y; |
Hemant Modi