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 Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 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 + " ");
        }
    }
}

                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.