

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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.
- Related Questions & Answers
- How can I swap two strings without using a third 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
- Swapping two variable value without using third variable in C/C++
- 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?
- Perform MySQL SELECT INTO user-defined variable
- Select into a user-defined variable with MySQL
- MySQL ORDER BY with numeric user-defined variable?
- Get the maximum exam date using a user-defined variable in SQL
- Using User-Defined Variables in MySQL
- C program to swap two strings
- Using TreeMap to sort User-defined Objects in Java
Advertisements