Java Program to Swap two Strings without using temp

If we want to swap two Strings without using temporary variable,hence we can serve this purpose using this program.

lets take example:- String1-Noteshacker, String2- Website

After swapping it become: Website Noteshacker.

Explanation:

1. First we take two strings (s1=”Noteshacker”,s2=”Website”) as an input then we add/concatenate both of them and save it to String variable s1.

2. Now length of s1 is sum of s1+s2.i.e. s1=NoteshackerWebsite.i.e. length=17

3. Perform s1.substring(0, (s1.length() – s2.length()))and save it to string variable s2 by this we extracted Notehacker and save it to s2

4. Perform s1.substring(s2.length()) by this Website is extracted and save it to s1

5. Now s1=Website and s2=Noteshacker .

6. Simply print them s1 and s2,hence swapping done.

Algorithm/Explanation

  1. Start
  2. First take two String Input s1 and s2
    • s1=Noteshacker s2=Website
    • you can take user defined or static input
  3. Print original string Noteshacker Website
  4. Perform s1=s1.concat(s2). // s1=NoteshackerWebsite also length og s1=17
  5. Perform s2= s1.substring(0, (s1.length() – s2.length())); // 17-7 =10 ” Noteshacker “is extrated
  6. Performs1=s1=s1.substring(s2.length());// “Website “is extracted
  7. Print s1 and s2
  8. End

Program

/*
Java Program to Swap two String Without using temporary variable */
import java.util.Scanner;

public class SwappingString {
    public static void main(String args[]) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter String-1");
        String s1 = sc.nextLine();
        System.out.println("Enter String-2");
        String s2 = sc.nextLine();
        System.out.println("String Before Swapping:" + s1 + " " + s2);
        s1 = s1.concat(s2); //length=17
        s2 = s1.substring(0, (s1.length() - s2.length())); // 17-7 =10 noteshacker
        s1=s1.substring(s2.length());// Website
        System.out.println("String Before Swapping:" + s1 + " " + s2);
            }
}

Output:
Enter String-1
Noteshacker
Enter String-2
Website
String Before Swapping: Noteshacker Website
String Before Swapping: Website Noteshacker

Related Topics

Leave a Comment