How to Swap two numbers without using third variable in Java?

How to Swap two numbers without using third variable in Java?

Re: How to Swap two numbers without using third variable in Java?

A quick google search provides plenty of answers! Consider

Code:

`int x = 10, y = 5;`

// Code to swap 'x' and 'y'

x = x + y; // x now becomes 15

y = x - y; // y becomes 10

x = x - y; // x becomes 5

Note that this may be imprecise for non-integer numbers due to rounding errors.

For a detailed discussion see

http://javarevisited.blogspot.co.uk/...-tutorial.html

Re: How to Swap two numbers without using third variable in Java?

You can refer below resource for swapping two numbers,

https://www.flowerbrackets.com/java-...p-two-numbers/

Re: How to Swap two numbers without using third variable in Java?

Quote:

Originally Posted by

**arshi1586**
How to Swap two numbers without using third variable in Java?

The most "famous" way to do that I suppose is the XOR Swap Algorithm,

https://en.wikipedia.org/wiki/XOR_swap_algorithm

The algorithm is language independent and it works on bit patterns regardless of whatever the bits may represent at a higher level (such as for example a Java int). So you can swap any data type as long as it supports the XOR bitwise operator (and if it doesn't it's sometimes possible to cast to some type that does without actually copying anything).

Note that if you feel a need for algorithms like this in an application for performance reasons then Java probably isn't the optimal language.