Write a java program to swap two numbers
In this program, you will learn the technique of swapping two numbers using temporary variable in java programming language.
Exchanging the values stored in two variables is known as swapping. There are multiple ways to swap the values of two variables. It can be swapped using a temporary variable or simple or simple mathematical operations such as addition and subtraction or multiplication and division or bitwise XOR can also be used to perform the swap operation.
In the below program, two numbers 2.60f and 4.44f which are to be swapped are stored in variables: first and second respectively.
The variable is printed before swapping using println() to see the results clearly after swapping is done. Below given steps are followed swapping process. After completing swapping process and the variables are printed on the screen.
Remember, the only use of temporary is hold the value of first before swapping. You can also swap the numbers without using temporary.
- Program:
public class SwapNumbers {
public static void main(String[] args) {
float first = 2.60f, sec = 4.44f;
System.out.println("--Before swapping the numbers--");
System.out.println("First number = " + first);
System.out.println("Second number = " + sec);
// Value of first is assigned to temporary
float temporary = first;
// Value of sec is assigned to first
first = sec;
// Value of temporary (which contains the initial value of first) is assigned to sec
sec = temporary;
System.out.println("--After swapping the numbers--");
System.out.println("First number = " + first);
System.out.println("Second number = " + sec);
}
}
- Output:
--Before swapping the numbers-- First number = 2.6 Second number = 4.44 --After swapping the numbers-- First number = 4.44 Second number = 2.6
- Step:
Below are the simple steps we follow:
- Assign first to a temporary variable: temporary = first
- Assign second to first: first = second
- Assign temp to second: second = temporary
Let us understand with simple example,
first = 111, second = 222After line 1: temporary = firsttemporary = 111After line 2: first = secondfirst = 222After line 3: second = temporarysecond = 222