How to move an array element from one array position to another in Java?

Java 8Object Oriented ProgrammingProgramming

To move an element from one position to other (swap) you need to –

  • Create a temp variable and assign the value of the original position to it.
  • Now, assign the value in the new position to original position.
  • Finally, assign the value in the temp to the new position.

Example

Live Demo

import java.util.Arrays;

public class ChangingPositions {
   public static void main(String args[]) {
      int originalPosition = 1;
      int newPosition = 4;
      int [] myArray = {23, 93, 56, 92, 39};
      int temp = myArray[originalPosition];
      myArray[originalPosition] = myArray[newPosition];
      myArray[newPosition] = temp;
      System.out.println(Arrays.toString(myArray));
   }
}

Output

[23, 39, 56, 92, 93]
raja
Published on 08-Jan-2018 12:21:51
Advertisements