Learn a Java Program to swap two numbers in Java using multiplication operator , two variables, and three variables. This Java program swaps the values of two numbers using a temporary variable.
Code Explanation (Step-by-Step)
Using Multiplication Method
- Using n * 1 + m * 0, multiply n by 1 and m by 0.The result becomes 80, which is stored in variable d.
- Using m * 1 + n * 0, multiply m by 1 and n by 0.The result becomes 70, which is stored in variable c.
Using Three Variables
- Store the value of a in the temporary variable temp.
- Assign the value of b to a using a = b.
- Assign the value stored in temp to b using b = temp.
- The values of a and b are now swapped.
Using Two Variables
- Add both numbers using x + y and store the result in x.
- Subtract y from x using y = x – y. Now, y contains the original value of x.
- Subtract the new value of y from x using x = x – y. Now, x contains the original value of y.
- The values of x and y are now swapped.
public class SwapNumber {
public static void main(String[] args) {
// Using Mathematical Assignment Method
int m = 70;
int n = 80;
int d = n * 1 + m * 0;
System.out.println("After swap value m :- " + d);
int c = m * 1 + n * 0;
System.out.println("After swap value n :- " + c);
System.out.println();
// Using Three Variables
int a = 30;
int b = 50;
int temp = a;
a = b;
b = temp;
System.out.println("After swap value a :- " + a);
System.out.println("After swap value b :- " + b);
System.out.println();
// Using Two Variables
int x = 35;
int y = 45;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swap value x :- " + x);
System.out.println("After swap value y :- " + y);
System.out.println();
}
}
Output :-
After swap value m :- 80
After swap value n :- 70
After swap value a :- 50
After swap value b :- 30
After swap value x :- 45
After swap value y :- 35
What Is Swapping of Two Numbers in Java?
Swapping two numbers in Java means exchanging the values of two variables. After swapping, the value stored in the first variable moves to the second variable, and the value stored in the second variable moves to the first variable.
For Example :
Before Swapping:
a = 10
b = 20
After Swapping:
a = 20
b = 10
Here are some Java-related programs that will help you understand Java concepts better:
FAQ
How do you swap two numbers in Java?
You can swap two numbers using a temporary variable, arithmetic operations, multiplication method, or bitwise XOR.
Which is the best method to swap two numbers?
Using a temporary variable is the simplest and most readable approach.
Can we swap two numbers without a third variable?
Yes, by using addition and subtraction or multiplication and division.
Is swapping two numbers asked in Java interviews?
Yes, it is a common Java interview question used to test basic programming concepts.