Amit
Amit

Reputation: 21

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";

Upvotes: 2

Views: 192

Answers (2)

Amit
Amit

Reputation: 21

After doing some wired practicals I got one more wried solution using Ternary Operator.

Solution: str1 = str2 + ( (str2= str1) != null ? "":"");

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

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.

Upvotes: 4

Related Questions