In this post, we will write a simple Java Program to swap two strings without using a third String variable.
The login is very simple, first add two string then use substring method to get sub-string from s1 and s2.
s1 = s1 + s2;
s2 = s1.substring(0, s1.length() - s2.length());
s1 = s1.substring(s2.length());
Java Program to Swap Two Strings without Third String Variable
/** * Java Program to Swap Two Strings without Third String Variable * @author javaguides.net * */ public class SwapTwoStrings { public static void main(String[] args) { String s1 = "javaguides"; String s2 = "javadesignpatterns"; display("Before Swapping :", s1, s2); // Swapping starts s1 = s1 + s2; s2 = s1.substring(0, s1.length() - s2.length()); s1 = s1.substring(s2.length()); // Swapping ends System.out.println("After Swapping :"); display("After Swapping :", s1, s2); } private static final void display(String str, String s1, String s2) { System.out.println(str); System.out.println("s1 : " + s1); System.out.println("s2 : " + s2); } }
Output:
Before Swapping :
s1 : javaguides
s2 : javadesignpatterns
--------------------------
After Swapping :
s1 : javadesignpatterns
s2 : javaguides
--------------------------
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Related String Programs
Note that these programs are asked in interviews.- Java program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course