Write a Java Program to Swap Strings using temp variable

By | 02.03.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

 

0 0 votes
Article Rating
Category: Java Programming String Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments