There are multiple way to swap two numbers in Java.
Using Multiplication Method :-
- Multiply n with 1 and m with zero, then n value will be present, m will be zero ,assign this value to d
- Multiply m with 1 and n with zero, then assign result to temp c
Using Three Variables :-
- Assign a to temp variable : temp = x
- Assign a to b : a = b
- Assign temp to b: b = temp
Using Two Variables :-
- Add x+y value and assign to x
- Subtract x-y value and assign to y
- Now here y value will be change.
- Subtract x-y value and assign to x
public class SwapNumber {
public static void main(String[] args) {
// using multiplication 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