Home / Programs / Swap two values inside a array using Java
Programming Example

Swap two values inside a array using Java

👁 107 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

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 Code

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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.