Write a program to swap two numbers using a temporary variable.

public class swap1
{
    public static void main()
    {
        int temp;
        int a=3;
        int b=9;
        temp=a;
        a=b;
        b=temp;
        System.out.println("After swapping, a="+a);
        System.out.println("After swapping, b="+b);
    }

After swapping,a will be=9
After swapping,b will be=3

Write a program to swap two numbers without using a temporary variable.

public class swap2
{
    public static void main()
    {
        int a=3;
        int b=9;
        a=a+b;
        b=a-b;
        a=a-b;
       System.out.println("After swapping, a="+a);
       System.out.println("After swapping, b="+b);
    }

After swapping,a will be=9
After swapping,b will be=3

rite a program

LEAVE A REPLY

Please enter your comment!
Please enter your name here