
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Two Strings Without Using Third User-Defined Variable in Java
In order to swap two strings i.e interchange the content of two strings we will use sub string method of string class in Java.First of all get the length of both strings before making any change in any of string.Now modify one string as concatenate both strings and assign to one string.
After this use sub string method of String class using begin index as length of new modified string 1 and last index as initial length of string 1.This will give us the swiped string 1 which contain content of string 2.
Now to get swiped string 2 again use sub string method here use begin index as 0 and last index as initial length of string 1
Example
public class SwapString { public static void main(String[] args) { String str1 = "Ram is a good boy."; String str2 = "Shyam is a good man."; String str3 = ""; System.out.println("string 1 : " + str1); System.out.println("string 2 : " + str2); int str1Length = str1.length(); int str2Length = str2.length(); str1 = str1 + str2; str3 = str1.substring(str1Length, str1.length()); str2 = str1.substring(0, str1Length); System.out.println("string 1 : " + str3); System.out.println("string 2 : " + str2); } }
Output
string 1 : Ram is a good boy. string 2 : Shyam is a good man. string 1 : Shyam is a good man. string 2 : Ram is a good boy.
Advertisements