This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Is this one of those silly interview questions that you got somewhere?
There's a trick to swap for example integer values without using a temporary value, using XOR.
It's a trick, and it has no practical value whatsoever, and it doesn't tell the interviewer anything about the candidate - only that he or she knows the trick. In other words, it's stupid to ask a question like that for a job interview.
You can create a Swapper class, but I think that would count as “temporary variables.” If, as Jesper says, you are asked that sort of question in an interview, and the job hangs on that question, maybe you should decline the offer.
santhosh kumar vk wrote:Could you please tell me how to swap two variable in java without using temp variable using any formula.
As Jesper says, you can swap two primitives using the XOR trick, and in C++ you can use the same to swap addresses; but Java doesn't have addresses, so if the variable is a reference type, it can't be done.
As others have said: Bad interview question - very bad.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
I first saw the XOR hack in 1973 or so. But I don't know if it ever had any real world justification. In those days, we were usually programming mainframes, and memory was insanely expensive, but even then, you could usually find a register or make a temp location on the stack.
Most modern processors have a swap instruction, usually used to implement a semaphore. So there is even less reason to use the XOR hack.
Pat Farrell wrote:I first saw the XOR hack in 1973 or so. But I don't know if it ever had any real world justification.
Well, one place where I think it still does is for linked lists, because you can store a doubly-linked node with only one pointer; although, according to this page, alternatives such as unrolled linked lists are probably just as good.
Ivan Jozsef Balazs
Joined: May 22, 2012
Pat Farrell wrote:
This sure looks like it violates the "no temp variables" rule to me.
My contribution was an example for C++ references and obviously not for the no-temp exercise.