How to Swap two numbers using two variable in Java

In Object-Oriented Programming, there are many ways to swap two numbers using two variables like using Arithmetic Operator, the Bitwise operator, etc.



Using Arithmetic Operator :

1.

import java.util.Scanner;
class Swap
{
 public static void main(String ar[])
 {
  Scanner s=new Scanner(System.in);
  System.out.println("Enter two no:-");
  int a=s.nextInt();
  int b=s.nextInt();
  System.out.println("Before Swap \n a="+a+" b="+b);
  a=a*b;
  b=a/b;
  a=a/b;
  System.out.println("After Swap \n a="+a+" b="+b);
 }
}

Output:

Enter two no:-
1
2
Before Swap
 a=1 b=2
After Swap
 a=2 b=1

2.
import java.util.Scanner;
class Swap
{
 public static void main(String ar[])
 {
  Scanner s=new Scanner(System.in);
  System.out.println("Enter two no:-");
  int a=s.nextInt();
  int b=s.nextInt();
  System.out.println("Before Swap \n a="+a+" b="+b);
  a=a+b;
  b=a-b;
  a=a-b;
  System.out.println("After Swap \n a="+a+" b="+b);
 }
}

Output:
Enter two no:-
1
2
Before Swap
 a=1 b=2
After Swap
 a=2 b=1

Comments