How to swap two strings without using the third variable in java?

The logic that can be implemented for this program is as follow:

Step1: Concatenate both strings and store them in the first variable. Ex. s1 = s1 + s2

Step2: s2 = s1.substring(0, s1.length() – s2.length());

Step3: s1 = s1.substring(s2.length());

Solution

Let’s see the complete logic below:

SwapTwoString.java

package com.javacodepoint.programs;

public class SwapTwoString {

	// Main method
	public static void main(String[] args) {

		// initializing two string variable
		String s1 = "abc";
		String s2 = "xyz123";

		System.out.println("Before swap :: s1=>" + s1 + ", s2=>" + s2);

		// step-1
		s1 = s1 + s2;

		// step-2
		s2 = s1.substring(0, s1.length() - s2.length());

		// step-3
		s1 = s1.substring(s2.length());

		System.out.println("After swap :: s1=>" + s1 + ", s2=>" + s2);

	}

}

OUTPUT:

Before swap :: s1=>abc, s2=>xyz123
After swap :: s1=>xyz123, s2=>abc

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

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