Swap two values inside a array using Java

Java Programming Language Array in java (Article) Array in java (Program)

89

To swap two values inside a Java array, you need to:

  1. Create a temporary variable to hold one of the values temporarily.
  2. Swap the values using this temporary variable.

Here is a simple example of how to swap two elements in a Java array:

Given Input:

Before Swap: 
10 20 30 40 50 

Expected Output:

After Swap: 
10 40 30 20 50

Program:

public class SwapExample {
    public static void main(String[] args) {
        // Sample array
        int[] arr = {10, 20, 30, 40, 50};

        // Indexes of the two elements to be swapped
        int index1 = 1; // Value 20 at index 1
        int index2 = 3; // Value 40 at index 3

        // Print the array before swapping
        System.out.println("Before Swap: ");
        for (int value : arr) {
            System.out.print(value + " ");
        }

        // Swap the two values using a temporary variable
        int temp = arr[index1];   // Store arr[index1] in temp
        arr[index1] = arr[index2]; // Replace arr[index1] with arr[index2]
        arr[index2] = temp;        // Replace arr[index2] with temp (original arr[index1])

        // Print the array after swapping
        System.out.println("\n\nAfter Swap: ");
        for (int value : arr) {
            System.out.print(value + " ");
        }
    }
}

Output:

Before Swap: 
10 20 30 40 50 

After Swap: 
10 40 30 20 50

Explanation:

  1. The array is initialized with values {10, 20, 30, 40, 50}.
  2. We specify index1 = 1 and index2 = 3, which means we are swapping the values 20 and 40.
  3. Using a temporary variable temp, the values at these two indices are swapped.
  4. After swapping, the array becomes {10, 40, 30, 20, 50}.

You can swap any two values in the array by changing the index1 and index2 values accordingly.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.