Saturday 18 June 2016

Swap two String variables in java without using a third variable.

First way to do it as below,

String s1 = "First";
String s2 = "Second";
    s1=s1+" "+s2;
s2=s1.split(" ")[0];
s1=s1.split(" ")[1];
System.out.println(s1 + " " + s2);


Another way to do it as,

String a="First";
String b="Second";

    a= a+b;
    b = a.substring(0,(a.length()-b.length())); 
    a = a.substring(b.length());

    System.out.println("a = "+a);
    System.out.println("b = "+b); 

one more way to do this as below,

String returnFirstString(String x, String y) {
    return x;
}

String a = "First"
String b = "Second"
a = returnFirstString(b, b = a); 
System.out.print(a+" "+b);


Another one more way we can do its as,

String s1 = "First";
String s2 = "Second";
AtomicReference<String> String1 = new AtomicReference<String>(s1);
AtomicReference<String> String2 = new AtomicReference<String>(s2);
String1.set(String2.getAndSet(String1.get()));
System.out.println(String1 + " " + String2);

Java Strings are implemented with references, so you need to swap their references.

No comments:

Post a Comment

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...