Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to swap two String variables without third variable.
To swap the contents of two strings (say s1 and s2) without the third, first of all concatenate them and store in s1. Now using the substring() method of the String class store the value of s1 in s2 and vice versa.
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
Advertisements
