File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Swap the variables!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Swap the variables!!" Watch "Swap the variables!!" New topic
Author

Swap the variables!!

Ravi Kumar Ravuru
Ranch Hand

Joined: Apr 18, 2002
Posts: 176
Hello Folks,
There are two variables suppose int x=10,y=20.I want to swap the variables without using a temporary variable.How can we do that?Please help me out.
Regards,
Ravi
Joe Pluta
Ranch Hand

Joined: Jun 23, 2003
Posts: 1376
Welcome to boolean logic 101.
x = x^y;
y = x^y;
x = x^y;
Nothing could be simpler .
Joe
P.S. Back in the olden days, we actually had to do this kind of stuff to save registers and avoid costly memory accesses. Honest!
Joe Pluta
Ranch Hand

Joined: Jun 23, 2003
Posts: 1376
Oh, and if you really want to be sick about it, try this:
x ^= y ^= x ^= y;
Joe
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Joe, you could slide those into the SCJP forum sometime


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Joe Pluta
Ranch Hand

Joined: Jun 23, 2003
Posts: 1376
For those of us who aren't really familiar with those forums, Barry, what exactly is the purpose of the SCJP forum, for example? How would I "slip this into" the forum? Just a question that might stimulate a little more participation from those of us who currently don't spend time in the certification forums.
Joe
Jason Menard
Sheriff

Joined: Nov 09, 2000
Posts: 6450
Not as cool as Joe's, but as a colleague of mine pointed out, this also works:
x = x + y
y = x - y
x = x - y
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Hi all
How about floats instead of int. Try this.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Swap the variables!!