In one interview, I got one question - How to swap two strings without using third variable. Below is the code:
String str1 = "Hello"; String str2 = "World";
We have to swap str2 = "Hello" & str1 = "World" without using third variable.
I have answered like str1 = "World" & str2 = "Hello". I did not see anything wrong in this assignment because if I assign like this I am just swapping the string literals. But he is not agreeing. If string literal is already there in string literal pool we can use the same to swap so in this case how my answer is wrong.
Once I am back from interview I have seen the solution little different like below code: How to swap two string variables in Java without using a third variable
I guess my interviewer expecting the solution as shown in the above link but which is not required to use subString method because same string literals can be used to swap.
I want to understand, is there anything is wrong in my answer/understanding.