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.

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

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019