Thursday, May 19, 2011

Swap two numbers without using third variable

Example:
Before Swap
number1=45 number2=33

After Swap
number1=33 number2=45



class Swap {
public static void main(String[] args) {
int number1=45,number2=33;
number1 = number1 + number2;
number2 = number1 - number2;
number1 = number1 - number2;
System.out.println("After swapping, number1= " + number1 + " and number2= "
+ number2);
}
}

4 comments:

suhas said...

Here is couple of more way to swap two numbers without using temp variable in Java

Udit said...
This comment has been removed by the author.
Udit said...

Three Methods to do Swapping without using temp variable

tachjava said...

One of the best explanation with example. Thanks a lot..

Cheers,
http://www.flowerbrackets.com/java-swap/