Q:

Java Program to swap two string variables without using third or temp variable

belongs to collection: Java String Programs

0

In this program, we need to swap two strings without using a third variable.

Str1: Good Str2: morning

Swapping two strings usually take a temporary third variable. One of the approach to accomplish this is to concatenate given two strings into first string.

Str1Str1 = Str1 + Str2= Goodmorning

Extract string 2 using substring (0, length(string1) - (string2)) i.e. in our case it will be substring(0, (11-4)). It will assign string Good to string 2 which is highlighted by green.

Str2 = Goodmorning

Extract string 1 using substring (length(string2)) i.e. we need to extract string from in length(string2) till end of the string. In our case it will be substring(4). It will assign string morning to string 1 which is highlighted by green.

Str1 = Goodmorning

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE Strings str1 = "Good ", str2 = "morning " to swap
  • STEP 3: PRINT "Strings before swapping " str1, str2
  • STEP 4: str1 =str1 + str2
  • STEP 5: EXTRACT str1 from indexes 0 to length (str1) - (str2) using substring function and store it in str2.
  • STEP 6: EXTRACT str1 from index length(str2) till end using substring function and store it in str1.
  • STEP 7: PRINT "Strings after swapping " str1, str2.
  • STEP 8: END

All Answers

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

Program:

public class SwapStrings     
{    
    public static void main(String[] args) {    
        String str1 = "Good ", str2 = "morning ";    
         System.out.println("Strings before swapping: " + str1 + " " + str2);    
        
        //Concatenate both the string str1 and str2 and store it in str1    
        str1 = str1 + str2;    
        //Extract str2 from updated str1    
        str2 = str1.substring(0, (str1.length() - str2.length()));    
        //Extract str1 from updated str1    
        str1 = str1.substring(str2.length());    
            
        System.out.println("Strings after swapping: " + str1 + " " + str2);    
    }    
}    

Output:

Strings before swapping: Good morning
Strings after swapping: morning Good

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

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Program to print smallest and biggest possible pal... >>
<< Java Program to separate the Individual Characters...