Java Program to Swap Two Strings Without Using Third Variable

In this quick article, we will see how to write a Java program to swap two strings with or without using the third variable.
First, we will see how to write a Java program to swap two strings using the third variable and then we will see how to write a Java program to swap two strings without using the third variable.

Video

For more explanation, watch below video:

Java Program to Swap Two Strings with Third Variable

package com.java.tutorials.programs;

public class SwapTwoStrings {

    public static void main(String[] args) {

        String s1 = "java";
        String s2 = "guides";

        System.out.println(" before swapping two strings ");
        System.out.println(" s1 => " + s1);
        System.out.println(" s2 => " + s2);

        String temp;
        temp = s1; // java
        s1 = s2; // guides
        s2 = temp; // java

        System.out.println(" after swapping two strings ");
        System.out.println(" s1 => " + s1);
        System.out.println(" s2 => " + s2);
    }
}
Output:
 before swapping two strings 
 s1 => java
 s2 => guides
 after swapping two strings 
 s1 => guides
 s2 => java

Java Program to Swap Two Strings Without Using Third Variable

Refer the comments which are self descriptive.
package com.java.tutorials.programs;

/**
 * Java Program to Swap Two Strings Without using Third Variable
 * @author Ramesh Fadatare
 *
 */
public class SwapTwoStrings {

    public static void main(String[] args) {

        String s1 = "java";
        String s2 = "guides";

        System.out.println(" before swapping two strings ");
        System.out.println(" s1 => " + s1);
        System.out.println(" s2 => " + s2);

        // step 1: concat s1 + s2 and s1

        s1 = s1 + s2; // javaguides // 10  

        // Step 2: store initial value of s1 into s2
        s2 = s1.substring(0, s1.length() - s2.length()); // 0, 10-6 //java

        // Step 3: store inital value of s2 into s1
        s1 = s1.substring(s2.length());

        System.out.println(" after swapping two strings ");
        System.out.println(" s1 => " + s1);
        System.out.println(" s2 => " + s2);
    }
}
Output:
 before swapping two strings 
 s1 => java
 s2 => guides
 after swapping two strings 
 s1 => guides
 s2 => java

Comments