Java Program to Swap Two Numbers

Write a Program to Swap two numbers.

Now, there are different way of doing it. By using temporary variable. Other swapping technique is done without using temporary variable. lets see them one by one.

Using Temporary Variable

public class SwapTwoNumbers {

    public static void main(String[] args) {

        float firstNum = 1.20f, secondNum = 2.45f;

        System.out.println("First number = " + firstNum);
        System.out.println("Second number = " + secondNum);

        // Value of firstNum is assigned to temp
        float temp = firstNum;

        // Value of secondNum is assigned to firstNum
        firstNum = secondNum;

        // Value of temp (which contains the initial value of firstNum) is assigned to secondNum
        secondNum = temp;

        System.out.println("First number = " + firstNum);
        System.out.println("Second number = " + secondNum);
    }
}
Output
First number = 1.2
Second number = 2.45

First number = 2.45
Second number = 1.2

Without using Temporary variable

class SwapTwoNumbers   
{  
    public static void main(String a[])   
    {   
        int x = 1.5; int y = 2.5;  
          
        System.out.println("Numbers before swapping numbers: "+x +" "+ y);  
       /*Swapping logic*/  
        x = x + y;   
        y = x - y;   
        x = x - y;   
        System.out.println("Numbers After swapping: "+x +"  " + y);   
    }   
}  
Output
Numbers before swapping numbers: 1.5  2.5
Numbers After swapping: 2.5  1.5

Leave a Reply