Swap Arrays in Java

  1. Use Numeric Operators to Swap Two Arrays in Java
  2. Use Bitwise Operators to Swap Two Arrays in Java
  3. Use Collections.swap() to Swap Two Elements of an Array in Java

In this article, we will look into different approaches to swap two arrays in Java. Instead of using a third variable to swap two arrays, we can use arithmetic and bitwise Operators.

Use Numeric Operators to Swap Two Arrays in Java

Here in the code given below, we have two arrays, a and b, which hold int type values. The length of the two arrays is the same.

We use arithmetic operators to swap a and b. For the first iteration, we have i equal to 0 and condition (i<2), so that the arithmetic statements inside the loop will be executed until the condition fails.

a[0] = a[0] - b[0] = 5-4 = 1

b[0] = a[0] + b[0] = 1+4 = 5

a[0] = GetAbsoluteValue(a[0] - b[0])= 1-5 = GetAbsoluteValue(-4) = 4

Math.abs() returns the absolute value of the passed argument. If the argument is not negative, it returns the argument, and if it is negative, then the negation of the argument is returned. This will work in the same manner for the second and third iteration.

import java.util.Arrays;
public class SwapArrayNumeric {
    public static void main(String[] args) throws Exception {
        int [] a = {5,9};
        int [] b = {4,3};
        System.out.println("a[] before swapping : "+Arrays.toString(a));
        System.out.println("b[] before swapping : "+Arrays.toString(b));
        for(int i = 0 ; i<a.length;i++){
            a[i] = a[i] - b[i];
            b[i] = a[i] + b[i];
            a[i] = GetAbsoluteValue(a[i] - b[i]);
        }
        System.out.println("a[] after swapping : "+Arrays.toString(a));
        System.out.println("b[] after swapping : "+Arrays.toString(b));

    }
    public static int GetAbsoluteValue (int a){
        return Math.abs(a);
    }
}

Output:

a[] before swapping : [5, 9]
b[] before swapping : [4, 3]
a[] after swapping : [4, 3]
b[] after swapping : [5, 9]

Use Bitwise Operators to Swap Two Arrays in Java

The bitwise XOR or ^ is a binary operator that returns bit by bit XOR of an input. If the corresponding bits are different, it gives 1, else 0. For the first iteration we have firstArr[0] = firstArr[0] ^ secondArr[0] = 2 ^ 6. The binary representation of 2 is 0010, and 6 is 0110.

Bitwise XOR of 2 and 6 is

0010 ^ 0110 = 0100 = 4 (in decimal)

firstArr[0] = firstArr[0] ^ secondArr[0] = 2 ^ 6 = 4

secondArr[0] = firstArr[0] ^ secondArr[0] = 4 ^ 6 = 2

firstArr[0] = firstArr[0] ^ secondArr[0] = 4 ^ 2 = 6

Hence we can swap elements of the array using the bitwise operators.

import java.util.Arrays;

public class SwapArrayBitwise {
    public static void main(String[] args) throws Exception {
        int [] firstArr = {2,4};
        int [] secondArr = {6,3};
        System.out.println("firstArr before swapping : "+Arrays.toString(firstArr));
        System.out.println("secondArr before swapping : "+Arrays.toString(secondArr));
        for(int i = 0 ; i<firstArr.length;i++){
            firstArr[i] = firstArr[i] ^ secondArr[i];
            secondArr[i] = firstArr[i] ^ secondArr[i];
            firstArr[i] = firstArr[i] ^ secondArr[i];
        }
        System.out.println("firstArr after swapping : "+Arrays.toString(firstArr));
        System.out.println("secondArr after swapping : "+Arrays.toString(secondArr));

    }
}

Output:

firstArr before swapping : [2, 4]
secondArr before swapping : [6, 3]
firstArr after swapping : [6, 3]
secondArr after swapping : [2, 4]

Use Collections.swap() to Swap Two Elements of an Array in Java

The swap() method of the Collections class swaps elements at the specified position in the specified list. We convert our firstArr into a list using Arrays.asList() and then pass it to the swap() method with positions 0 and 2. It swaps the word at index 0 with the word at index 2.

import java.util.Collections;
import java.util.List;

public class SwapTwoElements {
  public static void main(String[] args) throws Exception {
        String [] firstArr = {"Hello","World","Happy","Coding"};
        System.out.println("first[] before swapping : "+Arrays.toString(firstArr));
        List<String> a = Arrays.asList(firstArr);
        Collections.swap(a,0,2);

        System.out.println("first[] after swapping : "+Arrays.toString(firstArr));

    }
}

Output:

first[] before swapping : [Hello, World, Happy, Coding]
first[] after swapping : [Happy, World, Hello, Coding]
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java Array

  • Initialize a String Array in Java
  • Print 2D Array in Java