Generally speaking to swap two variables values, we need to define a third variable:
temp=a; a=b; b=temp;
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:
Post a Comment