'Swap two String in java using without using third variable and without any inbuild API in Java
Recently I have given an interview where they have asked me to swap two String without using any third variable and without using any String method like substring, replace or without using StringBuilder and StringBuffer.
Eg:
String str1 = "hello";
String str2 = "morning";
output:
String str1 = "morning";
String str2 = "hello";
Solution 1:[1]
Here's a trick that exploits assignment expressions (and evaluation order):
str2 = (new String[] { str1, (str1 = str2) })[0];
There surely can be many variations of that, but that does it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ernest_k |
