Swap Numbers in Java

 

Program to swap two numbers using third or temp variable.

/**
 * This program is used to swap to numbers using temp variable.
 * @author W3spoint
 */
public class SwapNumberExample {
  static void swapNumbers(int num1, int num2){ 
	int temp = num1;
        num1 = num2;
        num2 = temp;
	System.out.println("After swapping: "+ num1 + " and " + num2); 
  } 
 
  public static void main(String args[]){ 
	int num1 = 20; 
	int num2 = 30; 
	System.out.println("Before swapping:"+ num1 + " and " + num2); 
	//method call 
	swapNumbers(num1, num2); 
  }
}

Output:

Before swapping:20 and 30
After swapping: 30 and 20

 

Content Protection by DMCA.com
Please Share