Java Program to Swap Two Strings Without Using Third Variable

In this program, you will learn how to write a Java program to swap two strings without using the third variable.

Check out Java Program to Swap Two Strings with Third Variable.

Java Program to Swap Two Strings Without Using Third Variable

Refer to 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

References


Comments