beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java Program to Swap two numbers using Bitwise XOR Operator

By Chaitanya Singh | Filed Under: Java Examples

This java program swaps two numbers using bitwise XOR operator. Before going though the program, lets see what is a bitwise XOR operator: A bitwise XOR compares corresponding bits of two operands and returns 1 if they are equal and 0 if they are not equal. For example:

num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101

Let’s write this in a Java program:

Example: Swapping two numbers using bitwise operator

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String args[])
    {
        int num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");
        num1 = scanner.nextInt();
        System.out.print("Enter second number:");
        num2 = scanner.nextInt();
        /* To make you understand, lets assume I am going
         * to enter value of first number as 10 and second 
         * as 5. Binary equivalent of 10 is 1010 and 5 is
         * 0101
         */
        
        //num1 becomes 1111 = 15
        num1 = num1 ^ num2;
        //num2 becomes 1010 = 10
        num2 = num1 ^ num2;
        //num1 becomes 0101 = 5
        num1 = num1 ^ num2;
        scanner.close();
        System.out.println("The First number after swapping:"+num1);
        System.out.println("The Second number after swapping:"+num2);
    }
}

Output:

Enter first number:10
Enter second number:5
The First number after swapping:5
The Second number after swapping:10

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap