Skip to content

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

Swap two numbers in Java example shows how to swap two numbers using a temp variable and without using the third temp variable.

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

The logic of swapping two numbers using the temp variable in Java is simple. We use a temp variable to hold the value of the first variable, assign the second variable to the first, and then assign temp to the second variable. Please see below the given code example to do that.

Output

How to swap without using a third temp variable in Java?

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

Output

Please also check out the Java Math Tutorial with examples to know more about arithmetic operations.

This example is a part of the Java Basic Examples.

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

About the author

Leave a Reply

Your email address will not be published.