;

Java Program to Swap Two Numbers Using Third or Temporary Variable


Tutorialsrack 19/04/2021 Java

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

Java Program to Swap Two Numbers using Temporary Variable
//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);

	}
}
Output

--Before swap the numbers--

First number = 1.2

Second number = 2.45

--After swap the numbers--

First number = 2.45

Second number = 1.2

Understanding the Program

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.

  • First, the value of first is stored in the variable temporary (temporary = 1.20f).
  • Then, the value of the second is stored in the first (first = 2.45f).
  • And, finally, the value of temporary is stored in second (second = 1.20f).

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.


Related Posts



Comments

Recent Posts
Tags