In this article we are going to discuss a problem; this is one of the most commonly asked interview question of today. Write a program to swap two numbers without using a temporary variable.
 

Write a program to swap two numbers without using a temporary variable.

e.g. if int a=10 and int b=20 are two numbers than we have to swap their values to, a=20 and b=10 and using a and b only.

We can find the easiest solution by adding the value of b to a and than assigning b = a-b; now b would be a-b as well as shown in the code below:
package com.tbNext.byexample;

public class TBSwapTwoNumbersWithoutTemp {
	/*
	 * Swapping two variables without using a temp variable
	 */
	public static void main(String[] args) {
		int a = 4;
		int b = 10;
		System.out.println("Before Swapping a: " + a + " b:" + b);
		a = a + b;
		b = a - b;
		a = a - b;
		System.out.println("After Swapping a: " + a + " b:" + b);
	}

}

Output:

Before Swapping a: 4 b:10
After Swapping a: 10 b:4


That's it, we saw how to write a program to swap two numbers without using a temporary variable. In upcoming articles we will see more about Java and Related programming problems and solutions.
  • By Techburps.com
  • May 9, 2015
  • Programming