Swap two numbers using bitwise operator in java

In previous program we have learned how to program For nth Fibonacci Number in Java . In this article we will see how to swapping of two numbers without using third variable in java . We can swap two numbers in java using bitwise xor operator . Bitwise operator(^)  num1^num2 return 1 if corresponding bits are not equal otherwise return 0.

Now we will write a java program to swap two numbers without using third variable . We can swap two numbers in java using as

a = a^b

b = a^b

a=a^b

Let’s write a program to swap two numbers using bitwise xor operator in java.

public class SwapNumberUsingBitOperator {

	public static void main(String[] args) {
		int i = 6;
		int j = 4;
		System.out.println("Before swap i=" + i + "j=" + j);
		i = i ^ j;
		j = i ^ j;
		i = i ^ j;
		System.out.println("After Swap i=" + i + "j=" + j);
	}

}
Output :
Before swap i=6j=4
After Swap i=4j=6
In this program we have swap two numbers without using a temporary variable . We can swap two numbers in java by using other ways also. you can learn Top Core Java Coding / Programming Questions And Answers here. You can see good list of interview coding question with answers. You can see Top string coding question also.

Leave a Reply

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

64 − = 57