Java Swap Numbers

 

Program to swap two numbers using third or temp variable.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/**
* This program is used to swap to numbers using temp variable.
* @author W3schools360
*/
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);
}
}
/** * This program is used to swap to numbers using temp variable. * @author W3schools360 */ 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); } }
/**
 * This program is used to swap to numbers using temp variable.
 * @author W3schools360
 */
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Before swapping:20 and 30
After swapping: 30 and 20
Before swapping:20 and 30 After swapping: 30 and 20
Before swapping:20 and 30
After swapping: 30 and 20