Swap Without Variable Example Java Program


Definition

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 Without Variable Example Program

import java.util.Scanner;
 
class SwapWithoutVariable{
	public static void main(String args[]){
		int num1,num2;
		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);
		num1 = num1 + num2;
		num2 = num1 - num2;
		num1 = num1 - num2;
		System.out.println("After Swapping num1 = "+num1+" and num2 = "+num2);
	}
}

Sample Output

Output is:
Enter num1 and num2
67
78
Before Swapping num1 = 67 and num2 = 78
After Swapping num1 = 78 and num2 = 67