Swap With Variable Example Java Program


The act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory.

Swap With Variable Example Program

import java.util.Scanner;
class SwapWithVariable{
	public static void main(String args[]){
		int num1,num2,num3;
		System.out.println("Enter num1 and num2");
		Scanner in = new Scanner(System.in);
		num1 = in.nextInt();
		num2 = in.nextInt();
		System.out.println("Before Swapping num1 = "+num1+" and num2 = "+num2);
		num3 = num1;
		num1 = num2;
		num2 = num3;
		System.out.println("After Swapping num1= "+num1+" and num2 = "+num2);

Sample Output

Output is:
Enter num1 and num2
Before Swapping num1 = 45 and num2 = 34
After Swapping num1= 34 and num2 = 45