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 : :
need an explanation for this answer? contact us directly to get an explanation for this answer