Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to swap two values of 2 no.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to swap two values of 2 no.

Objective

Write a Java program to swap two values using a third temporary variable.

Algorithm / Approach

  1. Take two numbers as input from the user.
  2. Store them in variables x and y.
  3. Assign the value of x to a temporary variable temp.
  4. Assign the value of y to x.
  5. Assign the value of temp to y.
  6. 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);
  temp = x;
  x = y;
  y = temp;
  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

  • The variables x and y are read from the user.
  • A third variable temp is used as a temporary storage.
  • The value of x is stored in temp, then y is assigned to x.
  • Finally, the original value of x (from temp) is assigned to y, completing the swap.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Assigning x = y before saving the value of x in temp, causing data loss.
ADVERTISEMENT