Swap two Strings without using third Variable In Java

In this tutorial we will learn how to swap two strings without using third variable in java . We will use String.substring() method for swap two strings in java .

public class SwapTwoStringWithoutUsingVaraible {
	public static void main(String[] args) {
		String a = "mango";
		String b = "apple";
		a = a + b; //mangoapple
		b = a.substring(0, (a.length() - b.length())); 
              // b = "mangoapple".substring(0, 5) = "mango"
		a = a.substring(b.length(), (a.length())); 
              //a = "mangoapple".substring(5, 10) = "apple"
		System.out.println("a = " + a);
		System.out.println("b = " + b);
	}
}

Output :

a = apple
b = mango

This is java program of swap two strings without using third variable . You can practice more java string coding question for interview . You can see also must do coding question for java coding interview .

Reference :

Java Doc – String.substring()

Leave a Reply

Your email address will not be published. Required fields are marked *

35 − 26 =