Write a program to swap two strings without using third variable

public class SwapTwoStrings{

     public static void main(String []args){
        String str1 = "Temp";
        String str2 = "Variable";
        System.out.println("Strings Value before swap: str1 = " +
                                       str1 + " and str2 = "+ str2);
        str1 = str1 + str2;
        str2 = str1.substring(0,str1.length()-str2.length());
        str1 = str1.substring(str2.length());
        System.out.println("Strings Value after swap: str1 = " +
                                       str1 + " and str2 = "+ str2);
     }
}

Output: –

Strings Value before swap: str1 = Temp and str2 = Variable
Strings Value after swap: str1 = Variable and str2 = Temp

Leave a Reply

Your email address will not be published. Required fields are marked *