Swap two numbers with or without temporary variable in java

By | August 10, 2018

In this post we are going to learn Swap two numbers with or without temporary variable in java

Example 1:
Java program to swap or exchange two numbers with using temporary variable.

Example 2:
Java program to swap or exchange two numbers without using temporary variable.
Here We make use of Arithmetic Operator(+,-)

Example 3:

In this java program swapping two numbers using bitwise XOR operator. Before going though the program, lets understand what is a bitwise XOR operator?

A bitwise XOR basically compares corresponding bits of two operands and it returns 1 if they are not equal and 0(zero) if they are  equal. For example:

number1 ^ number2 compares corresponding bits of number1 and number2 and generates 1 if they are not equal, else it returns 0.

In our  case  it would return 29 which is equivalent to 00011101

I have tested  above programs for few inputs as below. You may check for other input as well 

That’s all about this topic How to swap or exchange two numbers with or without using any temporary variable in java
If you have any feedback or suggestion please feel free to drop in blow comment box.

Leave a Reply

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