- 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 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
- Related Articles
- Swap two Strings without using third user defined variable in Java
- How can I swap two strings without using a third variable in Java?
- 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#
- How to swap two arrays without using temporary variable in C language?
- Swap two Strings without using temp variable in C#
- Swapping two variable value without using third variable in C/C++
- How to Swap Two Variables using Python?
- How to swap two variables in JavaScript?
- Swap Numbers without using temporary variable in Swift Program?
- Swap two variables in one line in Java
- Swap two variables in one line using C#
- How to swap variables with destructuring in JavaScript?
- Swap two variables in one line in C/C+

Advertisements