- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I swap two strings without using a third variable in Java?
To swap the contents of two strings (say s1 and s2) without the third.
First of all concatenate the given two strings using the concatenation operator “+” and store in s1 (first string).
s1 = s1+s2;
The substring method of the String class is used to this method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is given.
Now using the substring() method of the String class store the value of s1 in s2 and vice versa.
s2 = s1.substring(0,i); s1 = s1.substring(i);
Example
public class Sample { public static void main(String args[]){ String s1 = "tutorials"; String s2 = "point"; System.out.println("Value of s1 before swapping :"+s1); System.out.println("Value of s2 before swapping :"+s2); int i = s1.length(); s1 = s1+s2; s2 = s1.substring(0,i); s1 = s1.substring(i); System.out.println("Value of s1 after swapping :"+s1); System.out.println("Value of s2 after swapping :"+s2); } }
Output
Value of s1 before swapping :tutorials Value of s2 before swapping :point Value of s1 after swapping :point Value of s2 after swapping :tutorials
- Related Articles
- Swap two Strings without using third user defined variable in Java
- Swap two Strings without using temp variable in C#
- How to swap two String variables without third variable.
- Write a Golang program to swap two numbers without using a third variable
- How to swap two numbers without using the third or a temporary variable using C Programming?
- How to swap two numbers without using a temp variable in C#
- Swapping two variable value without using third variable in C/C++
- How to swap two arrays without using temporary variable in C language?
- Swap Numbers without using temporary variable in Swift Program?
- How to compare two strings without case sensitive in Java
- Meta Strings (Check if two strings can become same after a swap in one string) in C++
- C program to swap two strings
- Swap two variables in one line in using Java
- How to concatenate two strings using Java?
- How can I generate two separate outputs using Random in Java

Advertisements