Java Program to swap two string variables without using third or temp variable.In this program, we need to swap two strings without using a third variable. Str1: Good Str2: morning Swapping two strings usually take a temporary third variable. One of the approach to accomplish this is to concatenate given two strings into first string. Str1Str1 = Str1 + Str2= Goodmorning Extract string 2 using substring (0, length(string1) - (string2)) i.e. in our case it will be substring(0, (11-4)). It will assign string Good to string 2 which is highlighted by green. Str2 = Goodmorning Extract string 1 using substring (length(string2)) i.e. we need to extract string from in length(string2) till end of the string. In our case it will be substring(4). It will assign string morning to string 1 which is highlighted by green. Str1 = Goodmorning Algorithm
Program:Output: Strings before swapping: Good morning Strings after swapping: morning Good Next TopicJava Programs |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India