Java program to swap two numbers

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:
  1. Assign first to a temporary variable: temporary = first
  2. Assign second to first: first = second
  3. Assign temp to second: second = temporary

Let us understand with simple example,

first = 111, second = 222
After line 1: temporary = first
temporary = 111
After line 2: first = second
first = 222
After line 3: second = temporary
second = 222

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here

0 comments