Java Program to Swap two Numbers - Swapping of Two Numbers in Java



Java Program to Swap two Numbers :

  • The swap() method is the Java Collections class is used to swap the numbers at the specified positions in the specified list.

Method 1 :

Sample Code

public class swapbymul 
{
  public static void main(String[] args) 
  {
    int a = 5, b = 10;
    System.out.println("Before swap a= " + a + " b= " + b);
    a = a * b; //a=50 (5*10)      
    b = a / b; //b=5 (50/10)      
    a = a / b; //a=10 (50/5)    
    System.out.println("After swap a= " + a + " b= " + b);
  }
}

Output

Before swap a= 5   b= 10
After swap   a= 10  b= 5

Method 2 :

Sample Code

public class swapbyadd 
                {
  public static void main(String[] args) 
  {
    int a = 5, b = 10;
    System.out.println("Before swap a= " + a + " b= " + b);
    a = a + b; //a=15 		(5+10)      
    b = a - b; //b=5 		(15-10)      
    a = a - b; //a=10		 (15-5)   
    System.out.println("After swap a= " + a + " b= " + b);
  }
}

Output

Before swap a= 5   b= 10
After swap   a= 10  b= 5

Method 3 :

Sample Code

public class swapbytemp 
                {
  public static void main(String[] args) 
  {
    int a = 5, b = 10, c;
    System.out.println("Before swap a= " + a + " b= " + b);
    c = b;
    b = a;
    a = c;
    System.out.println("After swap a= " + a + " b= " + b);
  }
}

Output

Before swap a= 5   b= 10
After swap   a= 10  b= 5

Related Searches to Java Program to Swap two Numbers - Swapping of Two Numbers in Java