+ 3

# int x=6; int y=9; x=y; System. out.println(x);

Please help me understand the concept of swapping. I am not able to understand how to figure out the answer??

10 Réponses

+ 20

Khushi Puri
Output for current code will be 9 not 6, check the quiz again if its the same then go to the Challenge again & report the quiz for 'Wrong Answer'
There is no case of swapping of variable value, instead we are changing value in x from 6 to 9.

+ 13

You can swap two numbers without using a temporary or third variable if you can store the sum of numbers in one number and then minus the sum with other number:
a = 3;
b = 5;
a = a + b; // 8
b = a - b; // 3
a = a - b; // 5
a = a + b;
b = a - b; // actually (a + b) - (b), so now b
is equal to a
a = a - b; // (a + b) - (a), now a is equal to b
now you have a = 5 and b = 3, so numbers are swapped without using a third or temp variable.

+ 3

Swapping basically means to interchange the values of 2 variable.
For eg. if x = 2 and y = 3 then after swapping the values will be x = 3 and y = 2.
For swapping two variable you can either use inbuilt swap method or you can use a temporary variable like this:-
int x,y,z;
x=2;
y=3;
z=x;
x=y;
y=z;
Here, value of x will be stored in z, value of y in x and then value of z will be stored in y which was actually having the value of x.
So basically now x will store value of y and vice versa.

+ 3

Though neither of these codes are java the concept is the same https://code.sololearn.com/wUK6ZD2GAgD6/?ref=app
https://code.sololearn.com/cVZzH1BSKAwj/?ref=app

+ 2

So output should be 9???

+ 2

Yes, in this case, it'll be 9.

+ 2

I encountered this question in a challenge.There it shows the output to be 6.I don't understand the reason for this.

+ 2

Answer is 9....value of x is getting overriden n no swapping occurs

+ 2

What does it mean -"value of x is getting overridden ..... "????

0

ye
yei