Java Program to Swap Two Elements in an Array based on Index

In this tutorial, we will discuss the Java program to swap elements based on their positions or indices. Whether you’re a coding newbie or a pro, you’ll dig the simple step-by-step guide. This question will be asked in the Java Interview and we got you covered as below tutorials:

Steps:

  1. Write a method which takes three parameters – swapElementsIndex(int[] arr, int index1, int index2)
  2. Using temp variable, we will swap the value of arr[index1] and arr[index2]
  3. Print the values of the array before and after the swap using Arrays.toString(arr)
  4. Then call swapElementsIndex(arr,0,4) in the main method

Java Program:

package TestAutomationCentral;

import java.util.Arrays;

public class ArraySwap {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        swapElementsIndex(arr,0,4);
    }

    public static void swapElementsIndex(int[] arr, int index1, int index2){
        System.out.println("Before Swap - " + Arrays.toString(arr));
        int temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
        System.out.println("After Swap - " + Arrays.toString(arr));
    }

}

Output:

Before Swap - [1, 2, 3, 4, 5]
After Swap - [5, 2, 3, 4, 1]
Share

Leave a Reply