Before starting your job search, look at these common Java interview questions asked during real interviews and understand the answers, but instead of memorizing the answers try to complete further research and come with your own personal solution for the interview question. The more prepared you are for what you will encounter, the more successful you will be. This collection of Java interview question could be also useful for software developers who need to interview Java developer.

Java Interview Question 10: Swap the values of two variables without using third variable

Have you already come across a situation where you need to swap the values of two variables without using third variable? I bet it was during an fresher interview for Java Developer position. As an interviewee you can think that it is a poorly chosen interview question and the only person who can answer this questions is the one who knows the trick in advance. I’m agree in some ways it is tough question, but it fits for purpose of evaluating Java developer’s analytical skills and problem solving abilities.

Generally speaking to swap two variables values, we need to define a third variable:


The generic answer on "swap the values of two variables without using third variable" questions is

a = a operation b
b = a inverse-operation b
a = a inverse-operation b

For example, the developer could write the following Java code
a = a + b; 
b = a - b; 
a = a - b;

Keep in mind that not all operations have an inverse that is well defined for all values that the operation is defined, for example * and / work until a or b is equal 0.

This tricky Java interview question can really catch beginner Java Developer of guard, especially if fresher mind is set to come up with straightforward answers. The way beginner Java Developer answers this question says a lot about interviewee thinking ability and is a great way to show off creativity and analytical skills.

No comments: