Saturday, June 12, 2010

How to swap two variables without using a third variable?

Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:

int a=5,b=10;a=a+b; b=a-b; a=a-b;

An other approach to the same question

You use an XOR swap.

for example:

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;




Java Interview Questions. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com