Java Swap of two data with out third variable Code

To swap two variables in Java without using a third variable, you can use arithmetic operations or bitwise XOR. Here’s how you can do it:

Using Arithmetic Operations

java

public class SwapWithoutThirdVariable {

    public static void main(String[] args) {

        int a = 30;

        int b = 40;

 

        System.out.println("Before Swap: a = " + a + ", b = " + b);

 

        // Swap using arithmetic operations

        a = a + b; // a now holds the sum of a and b

        b = a - b; // b now holds the original value of a

        a = a - b; // a now holds the original value of b

 

        System.out.println("After Swap: a = " + a + ", b = " + b);

    }

}

 

Using Bitwise XOR

java

public class SwapWithoutThirdVariable {

    public static void main(String[] args) {

        int a = 30;

        int b = 40;

 

        System.out.println("Before Swap: a = " + a + ", b = " + b);

 

        // Swap using bitwise XOR

        a = a ^ b; // a now holds the result of a XOR b

        b = a ^ b; // b now holds the original value of a

        a = a ^ b; // a now holds the original value of b

 

        System.out.println("After Swap: a = " + a + ", b = " + b);

    }

}

 

Explanation

  1. Arithmetic Operations:
    • a = a + b: Adds the values of a and b and stores the result in a.
    • b = a - b: Subtracts b from the new value of a (which is a + b), giving the original value of a.
    • a = a - b: Subtracts the new value of b (which is the original value of a) from a (which is a + b), giving the original value of b.
  2. Bitwise XOR:
    • a = a ^ b: Computes the XOR of a and b and stores it in a.
    • b = a ^ b: XORs the new value of a (which is a ^ b) with b, yielding the original value of a.
    • a = a ^ b: XORs the new value of a (which is a ^ b) with the new value of b (which is the original value of a), yielding the original value of b.

Ex-plain:

 

A       B       A^B (A XOR B)

0       0       0 (zero because operands are same)

0       1       1

1       0       1 (one because operands are different)

1       1       0




Both methods achieve the swap without using a temporary variable. The XOR method is more elegant and avoids potential issues with integer overflow, but the arithmetic method is often easier to understand.


Swap of two data with out third variable
Swap of two data with out third variable


Post a Comment

0 Comments