Java - Swapping of Two Numbers without using Third Variable in Java.
IncludeHelp
07 August 2016
Swapping of Two Variables - In this example we will swap value of first variable into second variable and value of second variable into first variable.
Generally we swap values of variables by using third variable in which we assign value of first variable into temporary or third variable, and then we assign value of second variable into first variable and finally assign value of third or temporary variable into first variable.
But in this code snippet, we will learn how to swap values of two variables without using third or temporary variable, this method of swapping is really very easy and takes less memory because we do not need to declare another temporary variable for swapping.
This method contains three steps: 1) Assign sum of first and second variable into first variable, 2) get value of first variable by subtracting second number from first number and 3) Get value of second variable by subtracting second variable from first variable. Finally you will get swapped values of two variables without using third variable.
Java Code Snippet - Swapping of Two Numbers without using Third Variable
//Java - Swapping of Two Numbers without using Third Variable in Java.
public class SwapTwoNumbers
{
public static void main(String args[]){
int number1=100,number2=200;
System.out.println("Numbers before swapping:");
System.out.println("number1: " + number1 +", number2: " +number2);
//swap without using third variable
number1=number1+number2;
number2=number1-number2;
number1=number1-number2;
System.out.println("Numbers after swapping:");
System.out.println("number1: " + number1 +", number2: " +number2);
}
}
Numbers before swapping:
number1: 100, number2: 200
Numbers after swapping:
number1: 200, number2: 100