Here You can learn 4 different approaches to swap two numbers in java programming language | codeYourslf 👨💻 | coding on mobile phone 📱.
Approach:- 1 "Swap two numbers in java with third variable"
package asicQuestion;
import java.util.Scanner;
public class swapNo {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number ");
int a = sc.nextInt();
System.out.println("Enter the second number: ");
int b = sc.nextInt();
System.out.println("The numbers after swap: "+a+"..."+b);
int temp = a;
a = b;
b = temp;
System.out.println("The numbers before swap: "+a+"..."+b);
}
}
Output
Approach:- 2 "Swap two numbers in java without using third variable"
import java.util.Scanner;
public class swapWithout3rdVar {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number ");
int a = sc.nextInt();
System.out.println("Enter the second number: ");
int b = sc.nextInt();
System.out.println("The numbers after swap: "+a+"..."+b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("The numbers before swap: "+a+"..."+b);
}
}
Approach:- 3 "Swap two numbers in java using multiplication and division"
package asicQuestion;
import java.util.Scanner;
public class swapByMultiply {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number ");
int a = sc.nextInt();
System.out.println("Enter the second number: ");
int b = sc.nextInt();
System.out.println("The numbers after swap: "+a+"..."+b);
a = a * b;
b = a / b;
a = a / b;
System.out.println("The numbers before swap: "+a+"..."+b);
}
}
Approach:- 1, Explanation
- Here first of all, we have to store the first value with an another variable i.e temp.
- Now we assign the second value to the first variable and the temp (value of first variable) value to the second variable.
- As a result the values are interchanged.
Approach:- 2, Explanation
I will explain this approach with a example, then only you can easily understood.
Let's initially a = 7 and b = 5
- In the first line
- a = a + b
- => a = 7 + 5
- => a = 12
- Now
- b = a - b
- => b = 12 - 5
- => b = 7
- And at last
- a = a - b
- => a = 12 - 7
- => a = 5
- See initially a and b was 7, 5 respectively, but after swap a become 5 and b become 7.
Approach:- 3 is also similar to approach:- 2, here we just have to replace addition (+) and substraction (-) with multiplication (*) and division (/).
Approach:- 4 ..
This is a funny approach to show output like two numbers have been swapped each other.
package asicQuestion;
public class funSwap {
public static void main(String[] args){
int a = 5, b = 7;
System.out.println("Original number: " + a + "..." + b);
System.out.println("After swap: " + b + "..." + a);
}
}
I have added this just for entertainment purposes. I personally develope this concept 😁. I have just interchanged the variables.
How is it please comment down below. ..