by Dinesh Thakur Category: Control Structures

Algorithm for Swap Two Variables Using XOR Operator:

step 1: Read a, b

step 2: a=a^b

step 3: b=b^a

step 4: a=a^b

step 5: Print a,b

step 6: Exit

Here is the Java Example for Swap Two Variables Using XOR Operator:

import java.util.Scanner;

public class SwapUsingXOR
{
                 public static void main(String args[])
           {
                  Scanner s=new Scanner(System.in);
                  int a,b;
                  System.out.println("Enter Two Numbers");
                  a=s.nextInt() ;
                  b=s.nextInt();
                  System.out.println("Before swap");
                  System.out.println("value of a is "+a+" value of b is "+b);
                  a=a^b;
                  b=b^a;
                  a=a^b;
                  System.out.println("After swap") ;
                  System.out.println("value of a is "+a+" value of b is "+b);
             }
}

Swap Two Variables Using XOR Operator

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article