Java Program to Swap Two Numbers without using Temporary Variable
In this java program, you'll learn how to swap two numbers without using temporary variable.
How to Swap Two Numbers without using Temporary Variable in Java?
Sourcecode
/*
Author : CodersEditor.com
Program : How to Swap Two Numbers without using Temporary Variable in Java?
*/
public class Main {
public static void main(String[] args) {
float firstNumber = 75.0f, secondNumber = 23.6f;
System.out.println("Numbers Before swapping");
System.out.println("First number = " + firstNumber + ", Second Number :" + secondNumber );
firstNumber = firstNumber - secondNumber;
secondNumber = firstNumber + secondNumber;
firstNumber = secondNumber - firstNumber;
System.out.println("Number After swapping");
System.out.println("First number = " + firstNumber + ", Second Number :" + secondNumber );
}
}
Output
Numbers Before swapping
First number = 75.0, Second Number :23.6
Number After swapping
First number = 23.599998, Second Number :75.0
Explanation
- In this java program, the two numbers are swapped without using any temporary variables. Instead, mathematical operators are used to swap the number.
- Before we swap, both the numbers are printed on the screen using System.out.println function.
- The value in the firstNumber is first stored in the temporaryVariable. Then, the value of the secondNumber is stored in the firstNumber. Finally, the value from the temporaryVariable is stored back to the second variable.
Remember, the only use of temporary is to hold the value of first before swapping. You can also swap the numbers without using temporary.
note
The use of temporaryVariable is to temporarily hold the value of the firstVariable during the swapping. There are ways to swap numbers without using temporary variables in java too. You will see them in the upcoming examples at CodersEditor.