# Swap Two Variables Using XOR Operator Using Java Example

by Dinesh Thakur Category: Control Structures

Algorithm for Swap Two Variables Using XOR Operator:

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);

}

}

``` Dinesh Thakur holds an B.C.A, 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.

Related Articles