In this post, we’ll look at how to write a java program to swap two numbers without using third variable. The java program will swap the two given integer numbers without using a local variable as a temporary variable. The reassigning variables are used to swap two numbers. The two variables will be used to swap these numbers by using variable value addition and subtraction.
Swap two numbers without using third variable in java
The following are the steps for swapping two numbers:
- subtract b from a and store in a a = a – b
- add b to a and store in b b = a + b
- subtract a from b and store in a a = b – a
Let’s look at number swapping with an example.
a = 4 ; b = 7 ; a = -3 ; b = 7 ; -- a = a - b a = -3 ; b = 4 ; -- b = a + b a = 7 ; b = 4 ; -- a = b - a
Java Program
package in.yawin; public class Swap { public static void main(String[] args) { int a = 4; int b = 7; System.out.println("Before Swapping 2 Numbers"); System.out.println("Number 1 is " + a); System.out.println("Number 2 is " + b); a = a - b; b = a + b; a = b - a; System.out.println("After Swapping 2 Numbers"); System.out.println("Number 1 is " + a); System.out.println("Number 2 is " + b); } }
Output
Before Swapping 2 Numbers Number 1 is 4 Number 2 is 7 After Swapping 2 Numbers Number 1 is 7 Number 2 is 4
Explanation
The java programme will make use of two numbers that are stored in two variables. In the two variables, the two numbers are swapped. Addition and subtraction are used to swap the values of these two variables. The second value is subtracted from the first and stored in variable one. The first variable will hold the difference between two values. Now The second value is multiplied by the first and stored in the second variable. The first value will be assigned to the second variable. Add the first and second values and store the result in the first variable. The second value will be assigned to the first variable. In this manner, two given numbers can be swapped without using a temporary variable in a Java programme.