Here's a Java program that swaps two numbers using bitwise XOR operation:
public class SwapNumbers { public static void main(String[] args) { int a = 5; // initialize first number int b = 10; // initialize second number System.out.println("Before swapping:"); System.out.println("a = " + a); System.out.println("b = " + b); // swap the numbers using bitwise XOR operation a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("After swapping:"); System.out.println("a = " + a); System.out.println("b = " + b); } }
In this program, we first initialize two variables a
and b
with the values we want to swap. We then perform the swap operation using bitwise XOR.
The basic idea behind using XOR for swapping two numbers is that XOR of two equal numbers is 0. By performing XOR operations on a
and b
, we can cancel out the original values of a
and b
and get the swapped values.
The program outputs the values of a
and b
before and after the swap.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.