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
- Take two numbers as input from the user.
- Store them in variables
xandy. - Assign the value of
xto a temporary variabletemp. - Assign the value of
ytox. - Assign the value of
temptoy. - 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
xandyare read from the user. - A third variable
tempis used as a temporary storage. - The value of
xis stored intemp, thenyis assigned tox. - Finally, the original value of
x(fromtemp) is assigned toy, completing the swap.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Assigning
x = ybefore saving the value ofxintemp, causing data loss.