Write a Java Program to Swap two strings without using temp variable

By | March 3, 2017

Java Program to Swap two strings


To swap two string variables without using third or temp variable, we use substring() method  or replace() method of String class.

substring() method has two overloaded forms :-

1) substring(int beginIndex)

It returns substring of a calling string starting with the character at the specified index and ending with the last character of the calling string.

2) substring(int beginIndex, int endIndex)

It returns substring of a calling string starting with the character at beginIndex (inclusive) and ending with the character at endIndex (exclusive).

We use both of these forms to swap two string variables without using third variable.


Java Program to Swap Two Strings using replace() method


SOURCE CODE  1: :

 

 

OUTPUT : :

 

 


Java Program to Swap Two Strings using substring() method


SOURCE CODE 2 : :

 

 

OUTPUT : :

 

Leave a Reply