In this java program, you will learn how to swap two numbers using a third or temporary variable in Java. In this program, The first variable uses a temporary variable for swapping, while the second variable doesn't use any temporary variables.
//Java Program to Swap Two Numbers Using Temporary Variable
public class JavaPrograms {
public static void main(String[] args) {
float first = 1.20f, second = 2.45f;
System.out.println("--Before swap the numbers--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
// Value of first is assigned to temporary
float temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap the numbers--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
--Before swap the numbers--
First number = 1.2
Second number = 2.45
--After swap the numbers--
First number = 2.45
Second number = 1.2
In the above program, two numbers 1.20f and 2.45f which are to be swapped are stored in variables: first and second respectively.
We printed the variables before swapping using println()
to see the results clearly after swapping is done.
This completes the swapping process and the variables are printed on the screen.
Remember, the only use of a temporary variable is to hold the value of the first variable before swapping. You can also swap the numbers without using a temporary variable.
Comments