Write a program to Swap Two Strings without Third String Variable


This Java program swaps the values of two strings without using a third variable. It does so by concatenating the two strings, then extracting the original values by using the substring() method. Here's a breakdown of how the swapping works:

  • Two strings s1 and s2 are declared and initialized with the values "Tutor" and "Joes", respectively.
  • The original values of s1 and s2 are printed to the console.
  • The values of s1 and s2 are concatenated using the + operator and assigned to s1.
  • The original value of s2 is extracted from s1 by using the substring() method with arguments 0 and s1.length() - s2.length(). This creates a substring of s1 that excludes the characters of s2.
  • The original value of s1 is extracted from s1 by using the substring() method with argument s2.length(). This creates a substring of s1 that starts at the end of s2.
  • The display() method is called with the swapped values of s1 and s2.
  • The swapped values of s1 and s2 are printed to the console by the display() method.

Source Code

class Swap_Without_Third
{
	public static void main(String[] args)
	{
		String s1 = "Tutor";
		String s2 = "Joes";
		System.out.println("Before Swap String 1 :"+s1);
		System.out.println("Before Swap String 2 :"+s2);
		s1 = s1 + s2;
		s2 = s1.substring(0, s1.length() - s2.length());
		s1 = s1.substring(s2.length());
		display(s1, s2);
	}
	private static final void display(String s1, String s2)
	{
		System.out.println("After Swap String 1 :"+s1);
		System.out.println("After Swap String 2 :"+s2);
	}
}

Output

Before Swap String 1 :Tutor
Before Swap String 2 :Joes
After Swap String 1 :Joes
After Swap String 2 :Tutor

Example Programs