Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to swap two values without using third variable.

Java Code Example — Basic Programs

ADVERTISEMENT

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

  1. Take two numbers as input and store them in x and y.
  2. Update x by adding y to it (x = x + y).
  3. Update y by subtracting the new y from the new x (y = x - y).
  4. Update x by subtracting the new y from the new x (x = x - y).
  5. 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 + y stores the sum of both numbers in x.
  • Next, y = x - y subtracts the original y from the sum, assigning the original x to y.
  • Finally, x = x - y assigns the original y to x.

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.
ADVERTISEMENT