Write a program to Swap Two Strings


  • Two string variables str1 and str2 are declared and initialized with "Computer" and "Science" respectively.
  • The initial values of str1 and str2 are printed using System.out.println().
  • A third string variable t_str is declared to temporarily store the value of str1.
  • The value of str1 is assigned to str2.
  • The value of t_str (which is the original value of str1) is assigned to str1.
  • The final values of str1 and str2 are printed using System.out.println().

Source Code

class Swap_String
{
	public static void main(String args[])
	{
		String str1 = "Computer";
		String str2 = "Science";
		String t_str;
		System.out.println("Before Swap String 1 :"+str1);
		System.out.println("Before Swap String 2 :"+str2);
		t_str = str1;
		str1 = str2;
		str2 = t_str;
		System.out.println("After Swap String 1 :"+str1);
		System.out.println("After Swap String 2 :"+str2);
	}
}

Output

Before Swap String 1 :Computer
Before Swap String 2 :Science
After Swap String 1 :Science
After Swap String 2 :Computer

Example Programs