Last Updated: 13 August, 2022
On this tutorial page we are going to learn how to write a Java program to swap two numbers without using a temporary variable.
We can swap two numbers without a temporary variable as follows :
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2 ;
Here, we first add num1 and num2 values and store the result in the num2 variable, then subtract num1 from num2 and store the result in the num2, and finally subtract num1 from num2 and store the result in the num1.
Let's see the given examples below:
Output
Before swapping numbers ---
First number: 10
Second number: 20
After swapping numbers ---
First number = 20
Second number = 10
Output
Enter First Number: 2000
Enter Second Number: 4000
After swapping numbers ---
First number = 4000
Second number = 2000
That's all guys, hope this Java Program is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com