Swap two numbers without a temporary variable in java

In this article, we will discuss how to swap two numbers without using a temp variable in Java.

swap numbers topjavatutorial.com
 

Swap numbers without temporary variable

 
We can swap two numeric values(like int, float, long etc) without a temporary variable as follows :
 
a = a + b ;
b = a – b ;
a = a – b ;
 

We can also use XOR(^) operator for the same :

a = a^b;
b = b^a;
a = a^b;
 

This is a frequently asked interview question. Let’s look at the corresponding java code.
 
 

Program to swap numbers without Using temp variable:

 

package com.topjavatutorial.app;

import java.util.Scanner;

public class ExampleSwapNumbers {

  public static void main(String[] args) {
    int first, second;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first number : ");
    first = sc.nextInt();
    System.out.println("Enter second number : ");
    second = sc.nextInt();
    sc.close();

    System.out.printf("\nBefore swapping : first = %d , second = %d\n",
        first, second);
    first = first + second;
    second = first - second;
    first = first - second;

    System.out.printf("\nAfter swapping : first = %d , second = %d", first,
        second);

  }
}

Output :

 
Enter first number :
10
Enter second number :
20

Before swapping : first = 10 , second = 20

After swapping : first = 20 , second = 10

 
 

Program to swap numbers using XOR operator:

package com.topjavatutorial;

public class ExampleSwapNumbers {

  public static void main(String[] args) {

    int first, second;

    first = 20;

    second = 50;

    //swap numbers using XOR
    
    first = second^first;

    second = second^first;

    first = first^second;

    System.out.println("first = " + first);
    System.out.println("second = " + second);

  }

}

Output :

 
first = 50
second = 20

 
 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

3 comments

  1. The addition/subtraction method works when addition of both the numbers do not go out of the int range

  2. Int first =5;
    Int second =3;
    first=first+second -first;
    second=first+second -second;

    This can also be done swap value without using another variable .

  3. […] How to swap two numbers without using a temp variable in java ? (Solution) […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: