Swap program in java

Java Program to Swap two Strings

Here, we will write a program that asks for two String inputs from the user and swaps them such that first string becomes second and vice-versa.

The basic idea is to use a Temporary variable that can be used to swap values from One String to Another String.

Java Code:

/* Program to enter two strings and print it after swapping both of them.*/
import java.util.*;
class SwapString
{
public static void main()
{
Scanner inp=new Scanner(System.in);

System.out.print("\n Enter First String: "); String s1=inp.nextLine(); System.out.print("\n Enter Second String: "); String s2=inp.nextLine(); String x="";

x=s1; s1=s2; s2=x;

System.out.println("After Swapping: "); System.out.println("First String: "+s1); System.out.println("Second String: "+s2); } }

Output:

Enter First String: Dipper

Enter Second String: Dapper

After Swapping: First String: Dapper Second String: Dipper

Swap program in java