# integer swapping without using temp variable, can you please reply me with a correct logic

Greenhorn
Posts: 9
public class Swap {
public static void main(String[] args)
{
int a = 9;
int b = 7;
a=b;
b = (a+b)-b;
System.out.println("After swapping a = " + a + " b = " + b);
Swap s = new Swap();
}
}

Anayonkar Shivalkar
Bartender
Posts: 1557
5

Welcome to CodeRanch!

Secondly, your class Swap does not contain any members and methods, so why are you creating an object of it (that too, at the end of main method)?

Now, coming to your point, before you write the code, take a pencil and paper, and try to understand the flow of swapping (without temporary variable).

Hint : you are doing a=b in your code. At that very instance, value of a is gone. All you have is 2 variables containing value of b, and further code is useless from swapping perspective.

I hope this helps.

Greenhorn
Posts: 9
Thank you sir, it really did help me
i just found out the logic to be
a=a+b;
b=a-b;
a=a-b;
thank you very much

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15559
46
Another way is XOR swap.

Note that while these are fun tricks, you should never use this in any real program, because code like this is unnecessarily complicated and confusing and you are not gaining anything in efficiency or performance.

Nikhil Sagar
Ranch Hand
Posts: 216
rahul aditya wrote:public class Swap {
public static void main(String[] args)
{
int a = 9;
int b = 7;
a=b;
b = (a+b)-b;
System.out.println("After swapping a = " + a + " b = " + b);
Swap s = new Swap();
}
}

Well, looks like interesting question for beginners like me.
hmm....,So, if you want a single line logic so i think the correct logic should be like this.....
MODERATOR ACTION: code removed

Nikhil Sagar, I've already asked you once: DontBeACodeMill(⇐click) and LetThemDoTheirOwnHomework(⇐click). You apologized and said you wouldn't do it again. Please honor that pledge. Thank you.

Campbell Ritchie
Sheriff
Posts: 50656
83
You do realise this is not something you ought to do in real-life code? I shall move this discussion to where we usually discuss such questions.

Nikhil Sagar
Ranch Hand
Posts: 216
Al rite, jeff sorry once again.