Java Program To Swap Two Numbers

Write Java program to swap two numbers

// WAP to swap two numbers using different methods

public class SwapNumber
{
    public static void main(String[] args) 
    {
        int a = 45 , b = 54, temp;


        System.out.println("Before swapping a = "+a+" and b = "+b);

        // METHOD - 1
        temp = a;
        a = b;
        b = temp;

        System.out.println("After swapping a = "+a+" and b = "+b+"\n");
        
        // METHOD - 2
        a = 44;
        b = 55;

        System.out.println("Before swapping a = "+a+" and b = "+b);
        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println("After swapping a = "+a+" and b = "+b);            
    }
}

Output:


<< Previous | Next >>


Leave a Reply

Your email address will not be published.