Swap Two Numbers using XOR in Java - The Coding Shala
Home >> Java Program >> Swap Two Numbers using XOR
Other Posts You May Like
In this post, we will learn how to Swap Two Numbers using XOR and will write a Java Program for the same.
Java Program to Swap Two Numbers using XOR
Swap two numbers without using an additional variable.
Example:
Input: a = 10;
b = 20;
Output: a = 20;
b = 10;
We can use XOR to swap the numbers.
Java Program:
public class SwapTwoNumbers { public static void main(String[] args) { int a = 10; int b = 20; System.out.println("Before swap"); System.out.println("a: " + a); System.out.println("b: " + b); //swap using xor a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("After swap"); System.out.println("a: " + a); System.out.println("b: " + b); } }
Output:
Before swap a: 10 b: 20 After swap a: 20 b: 10
- Java Program to Swap Two Numbers
- Java Program to Multiply Two Numbers
- Java Program to Generate Random Numbers
- Java Program to Reverse a String
- Java Program to Find Sum of Digits of a Number
Comments
Post a Comment