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

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



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]
Updated on: 2020-06-16T08:43:04+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements