top of page
Search
  • Writer's pictureAbhinaw Tripathi

Swap two Strings without using third user defined variable in Java


Ans: Given two string variables a and b, swap these variables without using temporary or third variable in Java. Use of library methods is allowed. Examples: Input: a = "Hello" b = "World" Output: Strings before swap: a = Hello and b = World Strings after swap: a = World and b = Hello Solution Algorithm: 1) Append second string to first string and store in first string: a = a + b 2) call the method substring(int beginindex, int endindex) by passing beginindex as 0 and endindex as, a.length() - b.length(): b = substring(0,a.length()-b.length()); 3) call the method substring(int beginindex) by passing b.length() as argument to store the value of initial b string in a a = substring(b.length()); Sample Code: import java.util.*; class SwapTest { public static void main(String args[]) { String a = "Hello"; String b = "World"; System.out.println("Strings before swap: a = " + a + " and b = "+b); a = a + b; b = a.substring(0,a.length()-b.length()); a = a.substring(b.length()); System.out.println("Strings after swap: a = " + a + " and b = " + b); } } Output: Strings before swap: a = Hello and b = World Strings after swap: a = World and b = Hello

9 views0 comments

Recent Posts

See All
bottom of page