my dog learned polymorphism*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Swap the variables!!" Watch "Swap the variables!!" New topic

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.
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 .
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;
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.
Jason Menard

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:
subject: Swap the variables!!
Similar Threads
Help with array List
Swapping two object in array
How will u swap three variable without using temp variable !??
swap without using temp variable
Java Questions in Interview