Q:

Write a Java Program to Swap Strings using temp variable

belongs to collection: Java String Solved Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Solved Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java Program to Swap two strings without u... >>
<< Java Program to Append(Concatenate) one string to ...