Java Program to swap two values without using third variable.
Objective
Write a Java program to swap two values without using a third variable.
Algorithm / Approach
- Take two numbers as input and store them in
xandy. - Update
xby addingyto it (x = x + y). - Update
yby subtracting the newyfrom the newx(y = x - y). - Update
xby subtracting the newyfrom the newx(x = x - y). - Print the swapped values.
Demo.java
import java.util.Scanner;
class Demo {
public static void main(String[] a)
{
int x,y,temp;
Scanner s=new Scanner(System.in);
System.out.print("Enter Num1: ");
x = s.nextInt();
System.out.print("Enter Num2: ");
y = s.nextInt();
System.out.print("Before Swapping");
System.out.println(" X="+x+" Y="+y);
x = x + y;
y = x - y;
x = x - y;
System.out.print("After Swapping ");
System.out.println(" X="+x+" Y="+y);
}
}
Expected Output
Enter Num1: 10 Enter Num2: 20 Before Swapping X=10 Y=20 After Swapping X=20 Y=10
Explanation of the Program
- This approach swaps two variables without requiring extra memory.
- First,
x = x + ystores the sum of both numbers inx. - Next,
y = x - ysubtracts the originalyfrom the sum, assigning the originalxtoy. - Finally,
x = x - yassigns the originalytox.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Getting the order of addition and subtraction mixed up.
- Not being aware of potential integer overflow if the numbers are extremely large.