Java Program to Swap Two Strings with Third Variable

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

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

References


Comments