Swap two Strings without using third variable

Swapping of two Strings without using third variable in Java

Swapping : Swapping simple means "Exchange". Swapping the values of two variables means exchanging the value of two variable with each other.

For Example :-

Input :-
str1 = "Java"
str2 = "Code"
 
Output after swapping :-
str1 = "Code"
str2 = "Java"

Program to swap two strings without using third variable given below :-

Program :-

import java.io.*;
import java.util.*;
class Swap_String
{
    public static void main(String args[])
    {
        Scanner in= new Scanner(System.in);
        String str1,str2;
        int l;
        System.out.println("Enter First Word");
        str1= in.nextLine(); //Input first word
        System.out.println("Enter Second Word");
        str2= in.nextLine(); //Input second word
        l= str1.length(); //storing length of first word
        str1= str1+str2; //combining both the words
        System.out.println("Combine : "+str1);
        str2= str1.substring(0,l);
        str1= str1.substring(l);
        System.out.println("~After Swapping~");
        System.out.println("First : "+str1);
        System.out.println("Second : "+str2);
    }//end of main method
}//end of class
 

For Proper Understanding Watch the Video :-

 
 

All the best :)
Keep Learning :)



Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

Tri-Automorphic Number in JAVA