3.6k views
2 votes
There are two String variables, s1 and s2, that have already been declared and initialized. Write some code that exchanges their values. Declare any other variables as necessary.

2 Answers

5 votes

Answer:

//here is code in java.

import java.util.*;

class Solution

{

// main method of class

public static void main (String[] args) throws java.lang.Exception

{

try{

// declare an initialize first string variables

String st1="hello";

// declare an initialize first string variables

String st2="world";

// create another string variable

String st3;

// exchange the value of both string variables

st3=st1;

st1=st2;

st2=st3;

System.out.println("value of first String after exchange: "+st1);

System.out.println("value of second String after exchange: "+st2);

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

declare and initialize two string variables.Create another string variable "st3". first assign value of "st1" to "st3" after then value of "st2" to "st1" and then assign value of "st3" to "st2". This will exchange the values of both the string.

Output:

value of first String after exchange: world

value of second String after exchange: hello

User Bubbler
by
5.4k points
5 votes

Answer:

The following are the code

string s1="san";

string s2="ran";

string temp; // other variable

temp=s1;// statement 1

s1=s2;// statement 2

s2=temp;//statement 3

Step-by-step explanation:

In this code we declared two string s1 , s2 and initialized them after that we declared an extra variable temp .

The statement 1 temp=s1 means that temp will store the value of s1 i.e "san". so temp="san";

The second statement 2 s1=s2 means that s1 will store the value of s2

i.e s1="ran";

The third statement 3 s2=temp means that s2 will store the value of temp.

i.e s2="san"

we see that s1 and s2 will exchange their value

Following are the code in c++

#include <iostream> // header file

#include<string>

using namespace std;

int main()// main function

{

string s1="san";

string s2="ran";

string temp;

cout<<"before exchange:"<<s1<<s2<<endl; // display before exchanging the value

temp=s1;

s1=s2;

s2=temp;

cout<<"after exchange:"<<s1<<s2<<endl;// display after exchanging the value

return 0;

}

Output:

before exchange:sanran

after exchange:ransan