Java Basic Examples

Swap two numbers with and without using temp variable in Java example

Swap two numbers with and without using temp variable in Java example shows 1. How to swap two numbers using temp and 2. How to swap two numbers without using temp variable in Java.

How to swap two numbers using temp variable in Java?

Logic of swapping two numbers using temp variable in Java is simple. We use temp variable to hold the value of first variable, assign second variable to the first , and then assign temp to second variable as given below.

Output

How to swap two numbers without using temp variable in Java?

Swapping two numbers without using temp variable is bit tricky. We need to use some math to do that. First, we add both the numbers and assign the sum to first variable. Now we subtract the second variable from the sum and assign it to the first variable (so that second variable contains the value of first and that is half job done). Then we again subtract value of second variable from the sum and assign it to the first variable (it will give value of first variable, because now second variable contains value of first variable).

Output

Please let us know your views in the comments section below.

 

Join 1000+ fellow learners! Enter your email address below: