Swap value of two numbers without using third variable in java

Write a java program to swap value of two numbers without using third variable.

import java.util.*;
public class swap2 
{
   public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        int t,a,b;
        System.out.println("enter a");
        a=s.nextInt();
        System.out.println("enter b");
        b=s.nextInt();
        System.out.println("a before swap"+a);
        System.out.println("b before swap"+b);
       /* a=a+b;
        b=a-b;
        a=a-b;*/
        //or
        b=a+b;
        a=b-a;
        b=b-a;
        System.out.println("a after swap"+a);
        System.out.println("b after swap"+b);
    } 
}

Leave a Reply

Your email address will not be published. Required fields are marked *