Swap Two Numbers in Java.

We can swap two numbers in Java with multiple approaches and in this article, we are going to discuss all those approaches in detail with code.


Approach 1: Using a third variable

In this approach, we use a third variable to swap the values of the two variables.


Java Example Code:

int a = 10;
int b = 20;
int temp;

temp = a;
a = b;
b = temp;

System.out.println("a = " + a); // Output: a = 20
System.out.println("b = " + b); // Output: b = 10

Approach 2: Using arithmetic operations

In this approach, we can use arithmetic operations like addition, subtraction, multiplication, and division to swap the values of the two variables.

Java Example Code:
int a = 10;
int b = 20;

a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20

System.out.println("a = " + a); // Output: a = 20
System.out.println("b = " + b); // Output: b = 10

Approach 3: Using the XOR operator

In this approach, we can use the XOR (^) operator to swap the values of the two variables.

Java Example Code:

int a = 10;
int b = 20;

a = a ^ b; // a = 30 (11110)
b = a ^ b; // b = 10 (01010)
a = a ^ b; // a = 20 (10100)

System.out.println("a = " + a); // Output: a = 20
System.out.println("b = " + b); // Output: b = 10
All these approaches have the same time complexity of O(1) as they take constant time to swap the values of two variables. (alert-success)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS