Swap two integers without using temp/third variable - Java Interview Questions -8

preview_player
Показать описание
Swap two integers without using temp/third variable:

Method 1 (Using Arithmetic Operators):
int x = 10, y = 5;

// Code to swap 'x' and 'y'
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5

Multiplication and division can also be used for swapping:
x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5

Method 2 (Using Bitwise XOR):
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)

===================================================
Subscribe to this channel, and press bell icon to get some interesting videos on Selenium and Automation:

Follow me on my Facebook Page:

Let's join our Automation community for some amazing knowledge sharing and group discussion:

Follow me on my Facebook Page:

Let's join our Automation community for some amazing knowledge sharing and group discussion on Telegram:

Paid courses (Recorded) videos:
📗 Get My Paid Courses at
Paid courses (Recorded) videos:
-------------------------------

✔️SOCIAL NETWORKS
--------------------------------

Support My Channel✔️Or Buy Me A Coffee
--------------------------------
✔️Thanks for watching!
देखने के लिए धन्यवाद
Благодаря за гледането
感谢您观看
Merci d'avoir regardé
Grazie per la visione
Gracias por ver
شكرا للمشاهدة
Рекомендации по теме
Комментарии
Автор

x = (x + y) - ( y = x );
Hi Naveen, this also would be an optimal solution in a single line

srknanduri
Автор

public static void swap(int x, int y){
x=x+y;
y=x-y;
x=x-y;
}
hope this helps

keshavjha
Автор

Sir I got a doubt as string is immutable how can we concatenate and assign to same string, just read on net that a new string is created and it reference is set to the object reference.

navathutejomai
Автор

hello Navin sir, i'm a EC student,
In XOR Swapping, X^Y = 1111 (15)
But Y = X^Y is 5 //Instead of 10
And X = X^Y is 10 // Instead of 5

programminghubbharat
Автор

Hi Naveen can make video to find second largest number in the array

tarikgulsever
Автор

Is xor operator is valid for all the inputs . As per the Xor operator it depends upon on placing of 0&1. I have tested it for many inputs and its working but amazing . please let me know how can anybody thinks like that.

tripathiakul
Автор

There is one more logic i tried after watching it:

x=(x+y) - (y=x);

sauravhateme
Автор

I think there is some mistake in multiplication without using third variable
x = x * y; // x now becomes 50
y = x / y; // y becomes 10 // instead of 5
x = x / y; // x becomes 5 // instead of 10

you have use int x=5, y=10

bharatvarshney
welcome to shbcf.ru