Last Updated: 13 August, 2022
On this tutorial page we are going to learn how to write a Java program to swap two numbers using a temporary variable.
We can swap two numbers using a temporary variable as follows :
temp = num1;
num1 = num2;
num2 = temp;
Here, we first assign num1 to the temp variable, then num2 to num1, and finally temp to num2.
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: 1500
Enter Second Number: 3000
After swapping numbers ---
First number = 3000
Second number = 1500
That's all guys, hope this Java Program is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com