Write a Java Program to Swap Strings using temp variable

By | March 2, 2017

Java Program to Swap Strings


 

Given two strings, we have to swap strings. For example, If First String = “ABC” and Second String = “abc” then after swapping First String = “abc” and Second String = “ABC”.

To swap strings in Java Programming, you have to first ask to the user to enter the two string, then make a temp variable of the same type. Now place the first string in the temp variable, then place the second string in the first, now place the temp string in the second.

Following Java Program ask to the user to enter the two strings to swap the strings, then display the result after swapping the strings:


SOURCE CODE : :

 

import java.util.Scanner;

public class Swap_Strings
{
    public static void main(String[] args)
    {
       
        Scanner scan = new Scanner(System.in);
        String str1, str2, temp; 
         
        System.out.print("First String : ");
        str1 = scan.nextLine();
        System.out.print("Second String : ");
        str2 = scan.nextLine();
        
        System.out.println("\nBefore Swapping :");
        System.out.print("Str1 = " +str1+ "\n");
        System.out.print("Str2 = " +str2+ "\n");
        
        temp = str1;
        str1 = str2;
        str2 = temp;
        
        System.out.println("\nAfter Swapping :");
        System.out.print("Str1 = " +str1+ "\n");
        System.out.print("Str2 = " +str2+ "\n");
    }
}

 

OUTPUT : :

 

First String : ABC
Second String : abc

Before Swapping : 
Str1 = ABC
Str2 = abc

After Swapping :
Str1 = abc
Str2 = ABC

 

Leave a Reply